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

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

compatibility 2.6

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