source: extensions/Piwecard/include/ecard.class.php @ 17566

Last change on this file since 17566 was 9342, checked in by tiico, 13 years ago

Version 1.0.4 :

  • Correct warning when option "active on user cats" is active
  • Add default mail for Guest eCard (in admin)

RU, IT, DE, LV language need to be updated

  • Property svn:eol-style set to native
File size: 17.6 KB
Line 
1<?php
2/*
3 * Plugin Name: Piwecard
4 * File :  ecard.php
5 */
6 
7global $user, $conf;
8
9class ecard
10{
11        var $debug = false;
12        var $my_config  ;
13        var $infos = array();   // conain all the info for the ecard : message; subject....
14
15        var $user_groups = array();
16       
17        // Class constructor
18        function ecard()
19        {
20                $this->load_config();
21        }
22
23       
24        // Load general configuration from config_database
25        function load_config() 
26        {
27
28                $query = '
29                  SELECT value
30                  FROM '.CONFIG_TABLE.'
31                  WHERE param = \'ecard\'
32                ;';
33
34                $result = pwg_query($query);
35
36            if($result) 
37                {
38                     $row = mysql_fetch_row($result);
39                     if(is_string($row[0])) 
40                         {
41                        $this->my_config = unserialize(($row[0]));
42                     }
43            }
44                $this->load_default_config();
45        }
46       
47        // Initialize default values of params
48        private function load_default_config()
49        {
50            include ECARD_INC_PATH.'default_values.inc.php';
51            foreach ($ecard_default_values as $key => $value) 
52                {
53//                      echo "value=".$key." \ ";
54                    if (!isset($this->my_config[$key]))         $this->my_config[$key] = $value;
55                }
56        }
57
58        // Save  general configuration to config_database
59        function save_config()
60        {
61                $query = '
62                  REPLACE INTO '.CONFIG_TABLE.'
63                  VALUES(
64                        \'ecard\',
65                        \''.serialize($this->my_config).'\',
66                        \'Configuration ecard\')
67                ;';
68
69                $result = pwg_query($query);
70
71                if($result) 
72                  return true;
73                else
74                  return false;
75        }
76       
77
78        // Retrieve user groups
79        function get_user_groups()
80        {
81                global $user;
82                if ($this->debug)
83                        foreach ($user as $id=>$val)
84                        {
85                                if (is_array($val))
86                                        foreach ($val as $id2=>$val2)
87                                                echo "user[".$id."][".$id2."]=".$val2."\n";
88                                else
89                                        echo "user[".$id."]=".$val."\n";
90                        }
91
92                $query = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . $user['id'] . ';';
93                if ($this->debug)               echo $query."\n";
94                $result = pwg_query($query);
95                while ($row = mysql_fetch_assoc($result))
96                {
97                  array_push($this->user_groups, $row['group_id']);
98                }
99               
100                if ($this->debug)
101                foreach ($this->user_groups as $gr)
102                        echo "Group=".$gr."\n";
103
104        }
105
106
107        function section_init_ecard()
108        {
109                global $tokens, $page;
110                if ($tokens[0] == 'ecard')
111                  $page['section'] = 'ecard';
112        }
113       
114        function index_ecard()
115        {
116                global $page;
117               
118                if (isset($page['section']) and $page['section'] == 'ecard')
119                {
120                /*
121                        foreach ($page as $i=>$p)
122                        echo "page[".$i."]=".$p." ;";
123                */
124                        include(ECARD_PATH . 'publish.php');
125                }
126        }
127
128        //Générer une chaine de caractère unique et aléatoire
129
130        private function random($car) {
131        $string = "";
132        $chaine = "abcdefghijklmnpqrstuvwxy0123456789";
133        srand((double)microtime()*1000000);
134        for($i=0; $i<$car; $i++) {
135        $string .= $chaine[rand()%strlen($chaine)];
136        }
137        return $string;
138        }
139
140        // NB of days between 2 dates "AAAA-MM-JJ HH:hh:ss"
141         function NbJours($debut, $fin) {
142
143          $tDeb = explode("-", substr($debut,0,strpos($debut, ' ')));
144          $tFin = explode("-", substr($fin,0,strpos($fin, ' ')));
145
146          $diff = mktime(0, 0, 0, $tFin[1], $tFin[2], $tFin[0]) - 
147                          mktime(0, 0, 0, $tDeb[1], $tDeb[2], $tDeb[0]);
148         
149          return(($diff / 86400));
150
151        }
152
153        function AjoutJours($debut, $jours, $soustrait = false) {
154          $tDeb = explode("-", substr($debut,0,strpos($debut, ' ')));
155          $tDebH = explode(":", substr($debut,strpos($debut, ' ')+1));
156          $tFin = "";
157
158                $nb_ans = (int)(($jours)/365);
159                $nb_mois = (int)(( ($jours)%365) / 31);
160                $nb_jours = (int)(( ($jours)%365) % 31);               
161
162                if ($soustrait)
163                        $tFin = date("Y-m-d H:m:s", mktime($tDebH[0], $tDebH[1], $tDebH[2], $tDeb[1] - $nb_mois, $tDeb[2] - $nb_jours, $tDeb[0] - $nb_ans));
164                else
165                        $tFin = date("Y-m-d H:m:s", mktime($tDebH[0], $tDebH[1], $tDebH[2], $tDeb[1] + $nb_mois, $tDeb[2] + $nb_jours, $tDeb[0] + $nb_ans));
166         
167          return($tFin);
168
169        }
170       
171        function parse($data, $_POST = NULL, $image_element = NULL)
172        {
173                include (ECARD_PATH.'include/config_param.inc.php');
174
175                $patterns = array();
176                $replacements = array();
177                foreach ($ecard_parse as $key => $value)
178                {
179                        array_push($patterns, $key); 
180                        array_push($replacements, $value);
181                }
182
183                return str_replace($patterns, $replacements, $data);
184        }
185       
186        // Get the number of ecard in the database
187        function get_nb_ecard()
188        {
189
190                $query = 'SELECT COUNT(DISTINCT numero) as nb FROM '.ECARD_TABLE
191                                . ' ORDER BY date'
192                                .';';
193                $result = pwg_query($query);
194                if ($result)
195                {
196                        $nb=mysql_fetch_assoc($result);
197                        return $nb['nb'];
198                }
199                else 
200                        return 0;
201        }
202
203        // Get the number of valid ecard in the database
204        function get_nb_valid_ecard()
205        {
206
207                $query = 'SELECT numero,date,duration  FROM '.ECARD_TABLE
208                                .';';
209                $result = pwg_query($query);
210                $count = 0;
211                while($ecard_info = mysql_fetch_assoc($result))
212                {
213                        if ( $ecard_info['duration'] == 0
214                                OR $this->NbJours($ecard_info['date'], date("Y-m-d H:m:s")) <= $ecard_info['duration']) // activ  ecard
215                                $count++;
216                }
217                return $count;
218        }
219       
220       
221        // Get ecard information into array
222        function get_ecard($ecard_id = null)
223        {
224                if ($ecard_id!== null)
225                {
226                        $query = '
227                                SELECT *
228                                FROM ' . ECARD_TABLE .'
229                                WHERE numero ="' . $ecard_id . '"
230                                LIMIT 1
231                        ';
232
233                        $result = pwg_query($query);
234                        if ($result)
235                                return  mysql_fetch_assoc($result);
236                        else 
237                                return false;
238                }
239
240        }
241
242        // Get ecard information into array
243        function is_valid($ecard_id = null, $param_date=false)
244        {
245                if ($ecard_id!== null)
246                {
247                        $ecard_info = $this->get_ecard($ecard_id);
248                        if ($ecard_info != false)
249                        {
250                       
251                                // Valid duration for an ecard
252                                $duration = ($param_date ? $this->my_config['activ'] : $ecard_info['duration']);
253                                if ($this->debug)
254                                {
255                                foreach ($ecard_info as $i=>$v)
256                                        echo "ecard[".$i."]=".$v." \ ";
257                                echo "NBjours = ".$this->NbJours($ecard_info['date'], date("Y-m-d H:m:s"))." -";
258                                echo "Activenb=".$this->my_config['activ']." -";
259                                }
260                               
261                               
262                                if (isset ($ecard_info) 
263                                        and $duration != 0              // 0 means always activ
264                                        and ($this->NbJours($ecard_info['date'], date("Y-m-d H:m:s")) > $duration)      // Inactiv ecard
265                                        )
266                                {
267                                        if ($this->debug)       echo "Invalid";
268                                        return false;
269                                }
270                                else 
271                                {
272                                        if ($this->debug)       echo "Valid";
273                                        return true;
274                                }
275                        }
276                        else
277                                return false;
278                }
279                else
280                {
281                        if ($this->debug)       echo "Invalid"; 
282                        return true;
283                }
284
285        }
286
287       
288        // delete one ecard
289        // force to delete valid ecard
290        function delete_ecard($ecard_id = null, $force = false)
291        {
292       
293                if ($ecard_id!== null)
294                {
295                        $ecard_info = $this->get_ecard($ecard_id);
296                        if ($this->debug)
297                        {
298                        foreach ($ecard_info as $i=>$v)
299                                echo "ecard[".$i."]=".$v." \ ";
300                        }
301                        if (isset ($ecard_info) 
302                                and ( ($this->NbJours($ecard_info['date'], date("Y-m-d H:m:s")) > $this->my_config['activ'])    // Inactiv ecard
303                                          OR $force                                                                                                                                                                     // Or force to delete even if activ
304                                         )
305                                )
306                               
307                        $query = '
308                                DELETE
309                                FROM ' . ECARD_TABLE .'
310                                WHERE numero ="' . $ecard_id  . '"
311                                ';
312
313//      echo "DELETE";
314                        pwg_query($query);
315                }
316                else
317                        return false;           
318       
319        }
320       
321        // Delete all invalid ecard
322        function delete_allinvalid_ecard()
323        {
324                $date = $this->AjoutJours(date("Y-m-d H:m:s"), $this->my_config['activ'], true);
325
326
327                $query = '
328                                DELETE
329                                FROM ' . ECARD_TABLE .'
330                                WHERE date < "' . $date  . '"
331                                ';
332//              echo "QUERY=".$query;
333//      echo "DELETE";
334                pwg_query($query);
335       
336        }
337       
338        // Add tpl to picture.php page to display ecard informations
339        function display_ecard_to_picture()
340        {
341                global $page, $user, $template, $conf;
342
343                // init user groups
344                $this->get_user_groups();
345
346        // Load language files
347        load_language('plugin.lang', ECARD_PATH);
348       
349                // CSS and JS file for the template
350                $css_file = "lightbox-form.css";
351                $template->block_html_head('', '<link rel="stylesheet" type="text/css" href="'.ECARD_PATH . 'template/'.$css_file.'">', $smarty, $repeat);
352                $template->block_html_head('', '<script src="'.ECARD_PATH .'js/lightbox-form.js" type="text/javascript"></script>', $smarty, $repeat);         
353
354               
355//              if (($page['section']) == 'categories' AND !empty($page['category']))           // only on category page!
356        if (isset($page['section']))
357                {
358               
359       
360                        $upper_names = null;
361           
362            if ( !empty($page['category']))
363            {
364                // get all upper categories from the image category to test
365                //      - if the parameter for "recursiv" is OK
366                //      - if the upper category is activated for this function
367                $query = 'SELECT *
368                            FROM '.CATEGORIES_TABLE.'
369                            WHERE id = '.$page['category']['id'].'
370                            ;';
371                $cat = mysql_fetch_assoc(pwg_query($query));
372                if (empty($cat))
373                {
374                    $upper_ids = null;
375                }
376                else
377                {
378                    foreach ($cat as $k => $v)
379                    {
380                        // If the field is true or false, the variable is transformed into a
381                        // boolean value.
382                        if ($cat[$k] == 'true' or $cat[$k] == 'false')
383                        {
384                          $cat[$k] = get_boolean( $cat[$k] );
385                        }
386                    }
387                    $upper_ids = explode(',', $cat['uppercats']);
388                }
389                        }
390           
391                        if ($this->my_config['user_cat'])       // !Function anly allowed on user image
392                        {
393                                // Check the category name, user name et img author
394                                // Get all name for upper categories and current category
395                if (isset($cat) and !empty($cat))
396                {
397                    $catname[0] = $cat['name'];
398                    if (isset($upper_ids) and $upper_ids != null)
399                    {
400                        $nb=1;
401                        foreach ($upper_ids as $upper_cat)
402                        {
403                            // Get upper cat info and store the name
404                            $cat_info = get_cat_info($upper_cat);
405                            $catname[$nb++] = $cat_info['name'];
406                            if ($this->debug)
407                                echo "Catname[".($nb-1)."]=".$catname[$nb-1]." <br>";
408                        }
409                    }
410                                }
411                                // Username or the current user
412                                $username = $user['username'];
413                               
414                                // author of the photo
415                                $authorname = "";
416                                $query = '
417                                                SELECT author
418                                                FROM '.IMAGES_TABLE.'
419                                                WHERE id = '.$page['image_id']
420                                                .' LIMIT 1'
421                                                .';';
422                                $result = pwg_query($query);
423                                if (isset($result))
424                                {
425                                        $img_infos = mysql_fetch_array($result);
426                                        $authorname = $img_infos['author'];
427                                }
428                                                               
429
430                        }                       
431                       
432/*
433                        foreach ($page as $k => $v)
434                        {
435                                if (is_array($v))
436                                        foreach ($v as $kk => $vv)
437                                                echo "page[".$k."][".$kk."]=".$vv." <br>";
438                                else
439                                        echo "page[".$k."]=".$v." <br>";
440                        }
441*/                     
442               
443                // only on available cats
444                        if ( $this->my_config['allcats']                // Available on all cats
445                                OR ( !empty($page['category']) AND in_array($page['category']['id'], $this->my_config['cats'])) // Available on specific cats
446                                OR ($this->my_config['recursive'] AND isset($upper_ids) AND                             // Available on upper cats this recursiv mode
447                                                (array_intersect($upper_ids, $this->my_config['cats']) != array()))
448                                OR      // Available based on usename
449                                        ($this->my_config['user_cat']
450                                                AND (in_array($username, $catname)      // Available user categories
451                                                                OR $username == $authorname)
452
453                                        ) 
454                                )
455                        {
456                        // and only available groups
457                                if (empty($this->my_config['groups']) 
458                                        or (!empty($this->my_config['groups'])
459                                                and (array_intersect($this->user_groups, $this->my_config['groups']) != array())) 
460                                        )
461                                {
462
463               
464                // Check if user is guest.
465                // In this case, force mail to default mail (in params)
466                if (is_a_guest())
467                {
468//                    $this->my_config['expmail_change'] = false; // Disable exp mail change
469                    if (!empty($this->my_config['defaultmail']))
470                        $user['email'] = $this->my_config['defaultmail'];
471                }
472                               
473                               
474                               
475                       
476                        // Template informations
477                                        $template->assign( 'ecard', array(
478                                                        'sujet' => l10n('ecard_send_title'),
479                                                        'message' => l10n('ecard_send_message'),
480                                                        'votrenom' => $user['username'],        //"votre nom",
481                                                        'votremail' => $user['email'],          //"votre mail (test@test.com)",
482                                                        'sonnom' => l10n('ecard_send_dest_name'),
483                                                        'sonmail' => l10n('ecard_send_dest_mail'),
484                                                        'copy'  => $this->my_config['send_copy'] ? 'checked="checked"' : '',
485                                                        'changemail' => ($this->my_config['expmail_change'] ? '' : 'disabled="disabled"')
486                                                        ));
487
488                        // TEmplate add for the active parameter choice by the user
489                                        if ($this->my_config['active_parameter'])       // Allowed for the user
490                                        {
491                                                $template->append('ECARD_ACTIV',array('ID' => 0,'NAME' => l10n('ecard_nolimit'),'SELECTED' => ($this->my_config['activ'] == 0 ? 'checked' : '')));
492                                                for($jj=5; $jj < 30; $jj+=5)
493                                                        $template->append('ECARD_ACTIV',array('ID' => $jj,'NAME' => $jj ,'SELECTED' => ($this->my_config['activ'] == $jj ? 'checked' : '')));
494                                        }
495                                                       
496                        // TEmplate add for the send method to be chose, by the user
497                                        // default : text
498                                        $template->append('ECARD_SEND',array('ID' => 0,'NAME' => l10n('ecard_maillink'),'SELECTED' => ($this->my_config['send_HTML'] ?  '' : 'checked')));
499                                        if ($this->my_config['send_HTML'])      // Allowed for the user
500                                        {
501                                                $template->append('ECARD_SEND',array('ID' => 1,'NAME' => l10n('ecard_mailhtml') ,'SELECTED' => ($this->my_config['send_HTML'] ? 'checked' : '')));
502                                        }
503                                               
504
505                                // Send the card
506                                        if (isset($_POST['ecard_submit']))
507                                        {
508                                       
509                                                $send_method = $_POST['ecard_send'];
510                                                // If conf dont allow to modify the %votremail param, force it to user mail
511                                                if (!isset($_POST['votremail']))
512                                                        $_POST['votremail'] = $user['email'];
513                                               
514                                                // Initialize the array for image element
515                                                $image_element = array();
516
517                                                // Get all image informations - to be replaced by a Core PWG function
518                                                $query = '
519                                                SELECT *
520                                                  FROM '.IMAGES_TABLE.'
521                                                  WHERE id = '.$page['image_id']
522                                                  .' LIMIT 1'
523                                                  .';';
524                        //                     echo $query;
525                                                $result = pwg_query($query);
526                                                if (isset($result))
527                                                        $image_element = mysql_fetch_array($result);
528                                               
529                                                // Generate random number
530                                                $image_element['next_element_id']  = $this->random(15);
531
532                                                // image infos
533                                                if ($this->my_config['ecard_showinfos'])
534                                                {
535                                                        if (isset($image_element['name']))
536                                                        {
537                                                                $image_element['imginfos'] = $image_element['name'];
538                                                                if (isset($image_element['author']))
539                                                                        $image_element['imginfos'] .= ' ('.$image_element['author'].')';
540                                                        }
541                                                               
542                                                }
543                                               
544                        if ($this->debug)       echo "Next_element=".$image_element['next_element_id']."\n";
545
546                                                $query = '
547                                                INSERT INTO ' . ECARD_TABLE .'
548                                                VALUES ( "'.$image_element['next_element_id'].'","'
549                                                                 .$_POST['votrenom'].'","'
550                                                                 .$_POST['sonnom'].'","'
551                                                                 .$_POST['votremail'].'","'
552                                                                 .$_POST['sonmail'].'","'
553                                                                 .$_POST['sujet'].'","'
554                                                                 .$_POST['message'].'",'
555                                                                 .$image_element['id'].',
556                                                                 now(),'
557                                                                 .(isset($_POST['ecard_activ']) ? $_POST['ecard_activ'] : $this->my_config['activ'])
558                                                                 .');';
559                                                // TO DO : add valid date (end date or duration) / add number (increment number) /
560
561                        if ($this->debug)                       echo $query."\n";
562                                                pwg_query($query);
563
564                                                // Complete the image_element array with Link for the ecard url to be added in the mail
565                                                set_make_full_url();
566                                                $chemin = embellish_url(get_absolute_root_url() . './index.php?/ecard/'.$image_element['next_element_id']);
567                                                $image_element['chemin'] = $chemin;
568                                                unset_make_full_url();
569        //                                      echo "chemin = ".$chemin."\n" ;
570
571                                                // Complete the image_element with the url to point to the image url
572                                                set_make_full_url();
573                                                $image_element['url_picture'] = duplicate_picture_url(
574                                                  array(
575                                                        'image_id' => $image_element['id'],
576                                                        'image_file' => $image_element['file']
577                                                  ),
578                                                  array('start')
579                                                );
580                                                unset_make_full_url();
581                                               
582
583                                                $sujetdumail = htmlspecialchars_decode($this->parse( $this->my_config['subject_link'], $_POST));
584                                               
585                                                switch($send_method)
586                                                {
587                                                case 0 : // text
588                                                        // Get the standard message (in admin param) and parse it with the informations
589                                                        $messagemail =  stripslashes(htmlspecialchars_decode($this->parse($this->my_config['message_link'], $_POST, $image_element)));
590
591                                                        $mail_arg=array('from' => $_POST['votremail'],
592                                                                                        'subject' => $sujetdumail,
593                                                                                        'content' => $messagemail,
594                                                                                        'content_format' => "text/plain",
595                                                                                        'email_format' => "text/html"
596                                                                                        );
597                                               
598                                                        break;
599                                                case 1 : // html
600                                                        $messagemailHTML =  stripslashes(htmlspecialchars_decode($this->parse($this->my_config['message_HTML'], $_POST, $image_element)));
601
602                                                        $mail_arg=array('from' => $_POST['votremail'],
603                                                                                        'subject' => $sujetdumail,
604                                                                                        'content' => $messagemailHTML,
605                                                                                        'content_format' => "text/html",
606                                                                                        'email_format' => "text/html"
607                                                                                        );
608                                                        if ($this->debug)               echo "messagemailHTML=".$messagemailHTML."\n";
609                                                        break;
610                                                }
611                                               
612                                                // Add the copy to expe if param.
613                                                if (isset($_POST['copy']))      // send copy to sender
614                                                        $mail_arg['Bcc'] = array((isset($_POST['votremail']) ? $_POST['votremail'] : $user['email']));
615                                               
616                                                // SEnd the mail
617                                                pwg_mail($_POST['sonmail'], $mail_arg);
618                                               
619                                        }
620                                        $template->set_filenames(array('ecard' =>  ECARD_ROOT.'/template/ecard.tpl'));
621                                        $template->concat('COMMENT_IMG', $template->parse('ecard', true));
622                                }
623                        }
624                }
625        }
626
627       
628        // Activation page administration
629        function ecard_admin_menu($menu)
630        {
631            array_push($menu,
632               array(
633                    'NAME' => ECARD_NAME,
634                    'URL' => get_admin_plugin_menu_link(ECARD_ADMIN_PATH.'admin.php')
635                ) 
636            );
637            return $menu;
638        }
639       
640       
641}
642
643?>
Note: See TracBrowser for help on using the repository browser.