source: extensions/Piwecard/include/piwecard.class.php @ 31331

Last change on this file since 31331 was 30184, checked in by plg, 10 years ago

compatibility Piwigo 2.7

set the config during activation, instead of loading it from default
config file on each page reload.

  • Property svn:eol-style set to native
File size: 19.4 KB
Line 
1<?php
2global $user, $conf;
3
4class Piwecard {
5        var $config;
6        var $user_groups = array();
7       
8        /**
9         * Constructor
10         */
11        function __construct() {
12                $this->get_config();
13        }
14       
15        /**
16         * Load configuration from database
17         * Assign value to the variable $config
18         */
19        function get_config() {
20                $query = 'SELECT value FROM '.CONFIG_TABLE.' WHERE param="piwecard";';
21                $result = pwg_query($query);
22
23            if(isset($result)) {
24                        $row = pwg_db_fetch_row($result);
25                        if(is_string($row[0])) {
26                                $this->config = unserialize(($row[0]));
27                        }
28            }
29        }
30       
31        /**
32         * Load default configuration from the install directory
33         * Assign value to the variable $config
34         */
35        function get_default_config() {
36            require(PIWECARD_INSTALL_PATH.'default_values.inc.php');
37            foreach ($ecard_default_values as $key => $value) {
38                    if (!isset($this->config[$key]))
39                                $this->config[$key] = $value;
40                }
41        }
42
43        /**
44         * Get the default value of a parameter
45         * @param name of the parameter
46         * @return the default config of the parameter
47         */
48        function get_default_config_param($param) {
49            require(PIWECARD_INSTALL_PATH.'default_values.inc.php');
50                return $ecard_default_values[$param];
51        }
52       
53        /**
54         * Save the current configuration (ie the value of $config) to the database
55         */
56        function set_config() {
57                conf_update_param('piwecard', pwg_db_real_escape_string(serialize($this->config)));
58        }
59       
60        /**
61         * Initialize the section parameter of the page
62         */
63        function section_init_ecard() {
64                global $tokens, $page;
65               
66                if ($tokens[0] == 'ecard')
67                        $page['section'] = 'ecard';
68        }
69       
70        /**
71         * Load the ecard
72         */
73        function index_ecard() {
74                global $page;   
75                if (isset($page['section']) and $page['section'] == 'ecard') {
76                        include('publish.inc.php');
77                }
78        }
79
80        /**
81         * Get a random string
82         * @param Integer number of caracter of the random string
83         * @return String the random string
84         */
85        private function random($car) {
86                $string = "";
87                $chaine = "abcdefghijklmnpqrstuvwxy0123456789";
88                srand((double)microtime()*1000000);
89                for($i=0; $i<$car; $i++) {
90                        $string .= $chaine[rand()%strlen($chaine)];
91                }
92                return $string;
93        }
94       
95        /**
96         * Parse the message
97         * @param String string to parse
98         * @param Array parser parameters
99         * @param Array an array with the id and the url of the image
100         * @return String the parsed string
101         */
102        function parse($data, $values, $image_element) {
103                include (PIWECARD_PATH.'include/parse_param.inc.php');
104
105                $patterns = array();
106                $replacements = array();
107                foreach ($ecard_parse as $key => $value) {
108                        array_push($patterns, $key); 
109                        array_push($replacements, $value);
110                }
111
112                return str_replace($patterns, $replacements, $data);
113        }
114       
115        /**
116         * Get the number of ecards in the database
117         * @return Integer number of ecards
118         */
119        function get_nb_ecard() {
120                $query = 'SELECT COUNT(DISTINCT ecard_id) AS nb FROM '.PIWECARD_TABLE.' ORDER BY date_creation;';
121                $result = pwg_query($query);
122               
123                if ($result) {
124                        $nb=pwg_db_fetch_assoc($result);
125                        return $nb['nb'];
126                } else 
127                        return 0;
128        }
129
130        /**
131         * Get the number of validecards in the database
132         * @return Integer number of valid ecards
133         */
134        function get_nb_valid_ecard() {
135                $query = 'SELECT COUNT(DISTINCT ecard_id) AS nb FROM '.PIWECARD_TABLE.' WHERE date_validity IS NULL OR date_validity > NOW();';
136                $result = pwg_query($query);
137               
138                if ($result) {
139                        $nb=pwg_db_fetch_assoc($result);
140                        return $nb['nb'];
141                } else 
142                        return 0;
143        }
144       
145        /**
146         * Get ecard informations into an array
147         * @param Integer ecard id
148         * @return Array informations of the ecard
149         */
150        function get_ecard($ecard_id) {
151                if ($ecard_id!== null) {
152                        $query = 'SELECT * FROM ' . PIWECARD_TABLE .' WHERE ecard_id="' . $ecard_id . '" LIMIT 1;';
153
154                        $result = pwg_query($query);
155                        if ($result)
156                                return  pwg_db_fetch_assoc($result);
157                        else 
158                                return false;
159                }
160        }
161
162        /**
163         * Is the ecard valid?
164         * @param Integer ecard id
165         * @return Boolean True if valid, False otherwise
166         */
167        function is_valid($ecard_id) {
168                if (isset($ecard_id)) {
169                        $ecard_info = $this->get_ecard($ecard_id);
170                        if (isset($ecard_info)) {
171                                // Valid duration for an ecard
172                                $date_validity = $ecard_info['date_validity'];
173                               
174                                if (isset($date_validity)) {
175                                        $now = new DateTime(date("Y-m-d H:i:s")); 
176                                        $date_validity = new DateTime($date_validity); 
177                                        if ($date_validity > $now)
178                                                return true;
179                                        else
180                                                return false;
181                                } else {
182                                        return true;
183                                }
184                        } else
185                                return false;
186                } else {
187                        return false;
188                }
189        }
190       
191        /**
192         * Delete one ecard
193         * @param Integer ecard id
194         */
195        function delete_ecard($ecard_id) {
196                if (isset($ecard_id)) {
197                        $query = 'DELETE FROM ' . PIWECARD_TABLE .' WHERE ecard_id="' . $ecard_id  . '";';
198                        pwg_query($query);
199                } else
200                        return false;
201        }
202       
203        /**
204         * Delete all invalid ecards
205         */
206        function delete_allinvalid_ecard() {
207                $query = 'DELETE FROM ' . PIWECARD_TABLE .' WHERE date_validity < NOW();';
208                pwg_query($query);
209        }
210       
211        /**
212         * Is the email valid?
213         * @param String email address
214         * @return Boolean True if valid, False otherwise
215         */
216        function is_valid_email($email_address) {
217                $syntax = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';
218               
219                if(preg_match($syntax, $email_address))
220                        return true;
221                else 
222                        return false;
223        }
224       
225        /**
226         * Add tpl to picture.php page to display ecard informations
227         */
228        function display_ecard_to_picture() {
229                global $page, $user, $template;
230
231                // Only on category page!
232                if (isset($page['section'])) {
233                        $upper_names = null;
234                       
235                        if (!empty($page['category'])) {
236                                // Gets all upper categories from the image category to test
237                                //      - if the upper category is activated for this function
238                                $query = 'SELECT * FROM '.CATEGORIES_TABLE.' WHERE id = '.pwg_db_real_escape_string($page['category']['id']).';';
239                                $cat = pwg_db_fetch_assoc(pwg_query($query));
240                               
241                                if (empty($cat)) {
242                                        $upper_ids = null;
243                                } else {
244                                        $upper_ids = explode(',', $cat['uppercats']);
245                                }
246                        }
247                       
248                        if ($this->config['authorized_cats'] == 'user') {       // !Function only allowed on user image
249                                if (isset($cat) and !empty($cat)) {
250                                        $catname[0] = $cat['name'];
251                                        if (isset($upper_ids)) {
252                                                $nb=1;
253                                                foreach ($upper_ids as $upper_cat) {
254                                                        $cat_info = get_cat_info($upper_cat);
255                                                        $catname[$nb++] = $cat_info['name'];
256                                                }
257                                        }
258                                }
259                                // Username or the current user
260                                $username = $user['username'];
261                                if (!$this->config['user_cats_case_sensitive'])
262                                        $catname = array_map('strtolower', $catname);
263                               
264                                // author of the photo
265                                $query = 'SELECT author FROM '.IMAGES_TABLE.' WHERE id = '.$page['image_id'].' LIMIT 1;';
266                                $result = pwg_query($query);
267                                if (isset($result)) {
268                                        $img_infos = pwg_db_fetch_assoc($result);
269                                        $authorname = $img_infos['author'];
270                                }
271                        }
272                       
273                        if ($this->config['authorized_groups_users'] == 'granted' OR $this->config['authorized_groups_users'] == 'denied') {
274                                $user_groups = array();
275                                $query = 'SELECT group_id FROM '.USER_GROUP_TABLE.' WHERE user_id='.$user['id'].';';
276                                $result = pwg_query($query);
277                                while ($row = pwg_db_fetch_assoc($result)) {
278                                        array_push($user_groups, $row['group_id']);
279                                }
280                        }
281                       
282                        // Only on available cats
283                        if (($this->config['authorized_cats'] == 'all')         //Parameter : all
284                                OR ($this->config['authorized_cats'] == 'selected' AND !empty($upper_ids) AND (array_intersect($upper_ids, $this->config['selected_cats']) != array())) //Parameter : selected
285                                OR      ($this->config['authorized_cats'] == 'user' AND $this->config['user_cats_case_sensitive'] AND (in_array($username, $catname) OR $username == $authorname)) //Parameter : user AND case sensitive
286                                OR      ($this->config['authorized_cats'] == 'user' AND !$this->config['user_cats_case_sensitive'] AND (in_array(strtolower($username), $catname) OR $username == $authorname)) //Parameter : user AND not case sensitive
287                        ) {
288                                if (($this->config['authorized_groups_users'] == 'all')         //Parameter : all
289                                        OR ($this->config['authorized_groups_users'] == 'granted' AND ((array_intersect($user_groups, $this->config['selected_groups']) != array()) OR in_array($user['id'], $this->config['selected_users']))) //Parameter : granted
290                                        OR ($this->config['authorized_groups_users'] == 'denied' AND ((array_intersect($user_groups, $this->config['selected_groups']) == array()) AND !in_array($user['id'], $this->config['selected_users']))) //Parameter : denied
291                                ) {
292                                        // Check if user is guest.
293                                        // In this case, force mail to default mail (in configuration)
294                                        if (is_a_guest()) {
295                                                if (!empty($this->config['default_guest_email']))
296                                                        $user['email'] = $this->config['default_guest_email'];
297                                        }
298                               
299                                        // Template informations
300                                        $template->assign('ecard', array(
301                                                        'title'                         => l10n('Title'),
302                                                        'message'                       => l10n('piwecard_message'),
303                                                        'sender_name'           => $user['username'],
304                                                        'sender_email'          => $user['email'],
305                                                        'recipient_name'        => l10n('piwecard_recipient_name'),
306                                                        'recipient_email'       => l10n('piwecard_recipient_email'),
307                                                        'copy'                          => $this->config['sender_copy'] ? 'checked="checked"' : '',
308                                                        'changemail'            => (!isset($user['email']) OR $this->config['sender_email_change']) ? '' : 'disabled="disabled"',
309                                                        'nb_max_recipients' => $this->config['nb_max_recipients'],
310                                                        )
311                                        );
312
313                                        // Template add for the active parameter choice by the user
314                                        if ($this->config['validity_choice']) {
315                                                foreach($this->config['validity'] as $validity) {
316                                                        $template->append('ecard_validity', array(
317                                                                                                                                                'id' => $validity,
318                                                                                                                                                'name' => ($validity == 0) ? l10n('piwecard_nolimit') : $validity.' '.l10n('piwecard_days'),
319                                                                                                                                                'selected' => ($this->config['validity_default'] == $validity ? 'checked' : '')
320                                                                                                                                        )
321                                                        );
322                                                }
323                                        } else {
324                                                $template->assign('ecard_validity_hidden', $this->config['validity_default']);
325                                        }
326
327                                        foreach ($this->config['email_format_authorized'] as $email_format) {
328                                                $template->append('ecard_email_format', array(
329                                                                                                                                        'id' => $email_format,
330                                                                                                                                        'name' => l10n('piwecard_email_format_'.$email_format),
331                                                                                                                                        'selected' => (($this->config['email_format_default'] == $email_format) ?  'checked' : ''),
332                                                                                                                                )
333                                                );
334                                        }
335                                       
336                                        $template->set_filenames(array('ecard_template' =>  PIWECARD_ROOT.'/template/ecard.tpl'));
337                                        $template->concat('COMMENT_IMG', $template->parse('ecard_template', true));
338
339                                        // Send the card
340                                        if (isset($_POST['ecard_submit'])) {
341                                                // If conf doesn't allow to modify the %yourmail% param, force it to user mail
342                                                if (!$this->config['sender_email_change'] and isset($user['email']))
343                                                        $_POST['ecard_sender_email'] = $user['email'];
344                                               
345                                                $email_format = $_POST['ecard_email_format'];
346                                               
347                                                //Check fields
348                                                if ($_POST['ecard_sender_name'] == ''
349                                                        OR $_POST['ecard_title'] == ''
350                                                        OR $_POST['ecard_message'] == '') {
351                                                        return;
352                                                }
353                                               
354                                                if ($_POST['ecard_sender_email'] == '' OR !$this->is_valid_email($_POST['ecard_sender_email']))
355                                                        return;
356                                               
357                                                // Initialize the array for image element
358                                                $image_element = array();
359
360                                                // Get all image informations
361                                                $query = 'SELECT * FROM '.IMAGES_TABLE.' WHERE id='.$page['image_id'].' LIMIT 1;';
362                                                $result = pwg_query($query);
363                                                if (isset($result))
364                                                        $image_element = pwg_db_fetch_assoc($result);
365                                               
366                                                // Generate random number
367                                                $next_element_id_random  = $this->random(64);
368                                                while (pwg_db_num_rows(pwg_query('SELECT ecard_id FROM '.PIWECARD_TABLE.' WHERE ecard_id="'.$next_element_id_random.'";')) != 0) {
369                                                        $next_element_id_random  = $this->random(64);
370                                                }
371                                                $image_element['next_element_id']  = $next_element_id_random;
372
373                                                // Image infos
374                                                if ($this->config['show_image_infos']) {
375                                                        if (isset($image_element['name'])) {
376                                                                $image_element['picture_infos'] = $image_element['name'];
377                                                                if (isset($image_element['author']))
378                                                                        $image_element['picture_infos'] .= ' ('.$image_element['author'].')';
379                                                        }
380                                                }
381                                               
382                                                // Complete the image_element array with Link for the ecard url to be added in the mail
383                                                set_make_full_url();
384                                                $ecard_url = embellish_url(get_absolute_root_url() . './index.php?/ecard/'.$image_element['next_element_id']);
385                                                $image_element['ecard_url'] = $ecard_url;
386                                                unset_make_full_url();
387                                               
388                                                // Complete the image_element with the url to point to the image url
389                                                set_make_full_url();
390                                                $image_element['picture_url'] = duplicate_picture_url(
391                                                        array(
392                                                                'image_id' => $image_element['id'],
393                                                                'image_file' => $image_element['file']
394                                                        ),
395                                                        array('start')
396                                                );
397                                                unset_make_full_url();
398                                               
399                                                // Send the mail
400                                                $recipient_infos = array_combine($_POST['ecard_recipient_name'], $_POST['ecard_recipient_email']);
401                                                foreach ($recipient_infos as $recipient_name => $recipient_email) {
402                                                        if ($recipient_name == '' OR $recipient_email == '' OR !$this->is_valid_email($recipient_email))
403                                                                continue;
404                                               
405                                                        $parse_list = array(
406                                                                                                'ecard_sender_name' => $_POST['ecard_sender_name'],
407                                                                                                'ecard_sender_email' => $_POST['ecard_sender_email'],
408                                                                                                'ecard_recipient_name' => $recipient_name,
409                                                                                                'ecard_recipient_email' => $recipient_email,
410                                                                                                'ecard_title' => $_POST['ecard_title'],
411                                                                                                'ecard_message' => $_POST['ecard_message'],
412                                                        );
413                                               
414                                                        $email_infos = array(
415                                                                                                'from_name' => $_POST['ecard_sender_name'],
416                                                                                                'from_email' => (isset($_POST['ecard_sender_email']) ? $_POST['ecard_sender_email'] : $user['email']),
417                                                                                                'to' => $recipient_email,
418                                                                                                'subject' => htmlspecialchars_decode($this->parse($this->config['email_subject'], $parse_list, $image_element)),
419                                                        );
420                                                       
421                                                        $email_message_text = stripslashes(strip_tags($this->parse($this->config['email_message']['text'], $parse_list, $image_element)));
422                                                        $email_message_html = stripslashes($this->parse($this->config['email_message']['html'], $parse_list, $image_element));
423                                                        switch($email_format) {
424                                                                case 'text': // text
425                                                                        $email_infos['message'] = array(
426                                                                                                                                        'text' => $email_message_text
427                                                                        );
428                                                                        break;
429                                                                case 'html': // html
430                                                                        $email_infos['message'] = array(
431                                                                                                                                        'text' => $email_message_text,
432                                                                                                                                        'html' => $email_message_html,
433                                                                        );
434                                                                default:
435                                                                        break;
436                                                        }
437                                                       
438                                                        // Add the copy to expe if param.
439                                                        if (isset($_POST['ecard_copy']))        // send copy to sender
440                                                                $email_infos['bcc'] = $email_infos['from_email'];
441
442                                                        $this->mail($email_infos);
443                                                       
444                                                        //Insert into database
445                                                        $insert = array(
446                                                                                'ecard_id'                      => $image_element['next_element_id'],
447                                                                                'sender_name'           => $_POST['ecard_sender_name'],
448                                                                                'recipient_name'        => $recipient_name,
449                                                                                'sender_email'          => $_POST['ecard_sender_email'],
450                                                                                'recipient_email'       => $recipient_email,
451                                                                                'title'                         => $_POST['ecard_title'],
452                                                                                'message'                       => $_POST['ecard_message'],
453                                                                                'image'                         => $image_element['id'],
454                                                                                'date_creation'         => date("Y-m-d H:i:s"),
455                                                        );
456                                                        if ($_POST['ecard_validity'] != '0') {
457                                                                $date = new DateTime();
458                                                                $date->modify("+".$_POST['ecard_validity']." day");
459                                                                $insert['date_validity'] = $date->format('Y-m-d H:i:s');
460                                                        }
461                                                        single_insert(PIWECARD_TABLE, $insert);
462                                                }
463                                        }
464                                }
465                        }
466                }
467        }
468
469  /**
470   * Encodes a string using Q form if required (RFC2045)
471   * mail headers MUST contain only US-ASCII characters
472   *
473   * This function was in Piwigo core include/functions_mail.inc.php, but
474   * was removed from version 2.6.
475   */
476  function encode_mime_header($str)
477  {
478    $x = preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
479    if ($x==0)
480    {
481      return $str;
482    }
483    // Replace every high ascii, control =, ? and _ characters
484    $str = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
485                        "'='.sprintf('%02X', ord('\\1'))", $str);
486   
487    // Replace every spaces to _ (more readable than =20)
488    $str = str_replace(" ", "_", $str);
489   
490    global $lang_info;
491    return '=?'.get_pwg_charset().'?Q?'.$str.'?=';
492  }
493       
494        /**
495         * Send an email
496         * @param Array informations of the email
497         */
498        function mail($email_infos) {
499                global $lang_info;
500                $template_mail = new Template(PIWECARD_MAIL_PATH.'template');
501                $smarty = $template_mail->smarty;
502               
503                $from = '"'.$email_infos['from_name'].'" <'.$email_infos['from_email'].'>';
504                $subject = $this->encode_mime_header(trim(preg_replace('#[\n\r]+#s', '', $email_infos['subject'])));
505                $boundary = '_----------='.md5(uniqid(mt_rand()));
506
507                $headers  = 'From: '.$from."\n";
508                $headers .= 'Reply-To: '.$from."\n";
509                if (!empty($email_infos['bcc']))
510                        $headers .= 'Bcc: '.$email_infos['bcc']."\n";
511                $headers .= 'X-Sender: <'.get_absolute_root_url().'>'."\n";
512                $headers .= 'X-Mailer: Piwigo Mailer'."\n";
513                $headers .= 'X-auth-smtp-user: '.$from."\n";
514                $headers .= 'X-abuse-contact: '.$from."\n";
515                $headers .= 'Date: '.date("D, j M Y G:i:s O")."\n";
516
517                $message = '';
518               
519                if (empty($email_infos['message']['html'])) {           //Text plain email
520                        $headers .= 'Content-Type: text/plain; charset="'.get_pwg_charset().'"'."\n";
521                        $headers .= 'Content-Transfer-Encoding: 8bit'."\n";
522                        $message = $this->get_text_message($email_infos['message']['text'], $smarty);
523                } else {
524                        $headers .= 'MIME-Version: 1.0'."\n";
525                        $headers .= 'Content-Type: multipart/alternative; boundary="'.$boundary.'"';
526                        $message .= 'This is a multi-part message in MIME format'."\n\n";
527                        $message .= '--'.$boundary."\n";
528                        $message .= 'Content-Type: text/plain; charset="'.get_pwg_charset().'"'."\n";
529                        $message .= 'Content-Transfer-Encoding: binary'."\n\n";
530                        $message .= $this->get_text_message($email_infos['message']['text'], $smarty);
531                        $message .= "\n\n";
532                        $message .= '--'.$boundary."\n";
533                        $message .= 'Content-Type: text/html; charset="'.get_pwg_charset().'"'."\n";
534                        $message .= 'Content-Transfer-Encoding: binary;'."\n\n";
535                        $message .= $this->get_html_message($email_infos['message']['html'], $smarty);
536                        $message .= "\n\n";
537                        $message .= '--'.$boundary."--\n";
538                }
539               
540                mail($email_infos['to'], $subject, $message, $headers);
541        }
542       
543        /**
544         * Get the content of the email when the format is plain text
545         * @param String the email message
546         * @param Smarty a smarty object
547         */
548        function get_text_message($message_text, $smarty) {
549                global $page, $conf;
550               
551                $message = $message_text;
552                $smarty->assign(array(
553                                                                'GALLERY_TITLE' => isset($page['gallery_title']) ? $page['gallery_title'] : $conf['gallery_title'],
554                                                                'GALLERY_URL' => get_absolute_root_url(),
555                                                                'MAIL' => get_webmaster_mail_address(),
556                                                        )
557                );
558                $message .= $smarty->fetch('mail_text.tpl');
559               
560                return $message;
561        }
562       
563        /**
564         * Get the content of the email when the format is html
565         * @param String the email message
566         * @param Smarty a smarty object
567         */
568        function get_html_message($message_html, $smarty) {
569                global $page, $conf;
570               
571                $border_config = $this->config['image_border'];
572                $smarty->assign(array(
573                                                                'BORDER' => (($border_config['display']) ? 'border-style: '.$border_config['style'].'; border-width: '.$border_config['width'].'; border-color: #'.$border_config['color'].';' : ''),
574                                                                'CONTENT_ENCODING' => get_pwg_charset(),
575                                                                'GALLERY_URL' => get_absolute_root_url(),
576                                                                'GALLERY_TITLE' => isset($page['gallery_title']) ? $page['gallery_title'] : $conf['gallery_title'],
577                                                                'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
578                                                                'MAIL' => get_webmaster_mail_address(),
579                                                                'MESSAGE_HTML' => $message_html,
580                                                        )
581                );
582                $message = $smarty->fetch('mail_html.tpl');
583               
584                return $message;
585        }
586}
Note: See TracBrowser for help on using the repository browser.