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

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

Version 1.0.2

  • Correct mail format error (slash)
  • Open function on specials pages (random items, best rates). For the moment, it's only possible if the plugin is active on all categories...
  • Property svn:eol-style set to native
File size: 16.7 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                // CSS and JS file for the template
347                $css_file = "lightbox-form.css";
348                $template->block_html_head('', '<link rel="stylesheet" type="text/css" href="'.ECARD_PATH . 'template/'.$css_file.'">', $smarty, $repeat);
349                $template->block_html_head('', '<script src="'.ECARD_PATH .'js/lightbox-form.js" type="text/javascript"></script>', $smarty, $repeat);         
350
351               
352//              if (($page['section']) == 'categories' AND !empty($page['category']))           // only on category page!
353        if (isset($page['section']))
354                {
355               
356       
357                        $upper_names = null;
358           
359            if ( !empty($page['category']))
360            {
361                // get all upper categories from the image category to test
362                //      - if the parameter for "recursiv" is OK
363                //      - if the upper category is activated for this function
364                $query = 'SELECT *
365                            FROM '.CATEGORIES_TABLE.'
366                            WHERE id = '.$page['category']['id'].'
367                            ;';
368                $cat = mysql_fetch_assoc(pwg_query($query));
369                if (empty($cat))
370                {
371                    $upper_ids = null;
372                }
373                else
374                {
375                    foreach ($cat as $k => $v)
376                    {
377                        // If the field is true or false, the variable is transformed into a
378                        // boolean value.
379                        if ($cat[$k] == 'true' or $cat[$k] == 'false')
380                        {
381                          $cat[$k] = get_boolean( $cat[$k] );
382                        }
383                    }
384                    $upper_ids = explode(',', $cat['uppercats']);
385                }
386                        }
387           
388                        if ($this->my_config['user_cat'])       // !Function anly allowed on user image
389                        {
390                                // Check the category name, user name et img author
391                                // Get all name for upper categories and current category
392                                $catname[0] = $cat['name'];
393                                if ($upper_ids != null)
394                                {
395                                        $nb=1;
396                                        foreach ($upper_ids as $upper_cat)
397                                        {
398                                                // Get upper cat info and store the name
399                                                $cat_info = get_cat_info($upper_cat);
400                                                $catname[$nb++] = $cat_info['name'];
401                                                if ($this->debug)
402                                                        echo "Catname[".($nb-1)."]=".$catname[$nb-1]." <br>";
403                                        }
404                                }
405                                // Username or the current user
406                                $username = $user['username'];
407                               
408                                // author of the photo
409                                $authorname = "";
410                                $query = '
411                                                SELECT author
412                                                FROM '.IMAGES_TABLE.'
413                                                WHERE id = '.$page['image_id']
414                                                .' LIMIT 1'
415                                                .';';
416                                $result = pwg_query($query);
417                                if (isset($result))
418                                {
419                                        $img_infos = mysql_fetch_array($result);
420                                        $authorname = $img_infos['author'];
421                                }
422                                                               
423
424                        }                       
425                       
426/*
427                        foreach ($page as $k => $v)
428                        {
429                                if (is_array($v))
430                                        foreach ($v as $kk => $vv)
431                                                echo "page[".$k."][".$kk."]=".$vv." <br>";
432                                else
433                                        echo "page[".$k."]=".$v." <br>";
434                        }
435*/                     
436               
437                // only on available cats
438                        if ( $this->my_config['allcats']                // Available on all cats
439                                OR ( !empty($page['category']) AND in_array($page['category']['id'], $this->my_config['cats'])) // Available on specific cats
440                                OR ($this->my_config['recursive'] AND isset($upper_ids) AND                             // Available on upper cats this recursiv mode
441                                                (array_intersect($upper_ids, $this->my_config['cats']) != array()))
442                                OR      // Available based on usename
443                                        ($this->my_config['user_cat']
444                                                AND (in_array($username, $catname)      // Available user categories
445                                                                OR $username == $authorname)
446
447                                        ) 
448                                )
449                        {
450                        // and only available groups
451                                if (empty($this->my_config['groups']) 
452                                        or (!empty($this->my_config['groups'])
453                                                and (array_intersect($this->user_groups, $this->my_config['groups']) != array())) 
454                                        )
455                                {
456                               
457                               
458                               
459                       
460                        // Template informations
461                                        $template->assign( 'ecard', array(
462                                                        'sujet' => l10n('ecard_send_title'),
463                                                        'message' => l10n('ecard_send_message'),
464                                                        'votrenom' => $user['username'],        //"votre nom",
465                                                        'votremail' => $user['email'],          //"votre mail (test@test.com)",
466                                                        'sonnom' => l10n('ecard_send_dest_name'),
467                                                        'sonmail' => l10n('ecard_send_dest_mail'),
468                                                        'copy'  => $this->my_config['send_copy'] ? 'checked="checked"' : '',
469                                                        'changemail' => ($this->my_config['expmail_change'] ? '' : 'disabled="disabled"')
470                                                        ));
471
472                        // TEmplate add for the active parameter choice by the user
473                                        if ($this->my_config['active_parameter'])       // Allowed for the user
474                                        {
475                                                $template->append('ECARD_ACTIV',array('ID' => 0,'NAME' => l10n('ecard_nolimit'),'SELECTED' => ($this->my_config['activ'] == 0 ? 'checked' : '')));
476                                                for($jj=5; $jj < 30; $jj+=5)
477                                                        $template->append('ECARD_ACTIV',array('ID' => $jj,'NAME' => $jj ,'SELECTED' => ($this->my_config['activ'] == $jj ? 'checked' : '')));
478                                        }
479                                                       
480                        // TEmplate add for the send method to be chose, by the user
481                                        // default : text
482                                        $template->append('ECARD_SEND',array('ID' => 0,'NAME' => l10n('ecard_maillink'),'SELECTED' => ($this->my_config['send_HTML'] ?  '' : 'checked')));
483                                        if ($this->my_config['send_HTML'])      // Allowed for the user
484                                        {
485                                                $template->append('ECARD_SEND',array('ID' => 1,'NAME' => l10n('ecard_mailhtml') ,'SELECTED' => ($this->my_config['send_HTML'] ? 'checked' : '')));
486                                        }
487                                               
488
489                                // Send the card
490                                        if (isset($_POST['ecard_submit']))
491                                        {
492                                       
493                                                $send_method = $_POST['ecard_send'];
494                                                // If conf dont allow to modify the %votremail param, force it to user mail
495                                                if (!isset($_POST['votremail']))
496                                                        $_POST['votremail'] = $user['email'];
497                                               
498                                                // Initialize the array for image element
499                                                $image_element = array();
500
501                                                // Get all image informations - to be replaced by a Core PWG function
502                                                $query = '
503                                                SELECT *
504                                                  FROM '.IMAGES_TABLE.'
505                                                  WHERE id = '.$page['image_id']
506                                                  .' LIMIT 1'
507                                                  .';';
508                        //                     echo $query;
509                                                $result = pwg_query($query);
510                                                if (isset($result))
511                                                        $image_element = mysql_fetch_array($result);
512                                               
513                                                // Generate random number
514                                                $image_element['next_element_id']  = $this->random(15);
515
516                                                // image infos
517                                                if ($this->my_config['ecard_showinfos'])
518                                                {
519                                                        if (isset($image_element['name']))
520                                                        {
521                                                                $image_element['imginfos'] = $image_element['name'];
522                                                                if (isset($image_element['author']))
523                                                                        $image_element['imginfos'] .= ' ('.$image_element['author'].')';
524                                                        }
525                                                               
526                                                }
527                                               
528                        if ($this->debug)       echo "Next_element=".$image_element['next_element_id']."\n";
529
530                                                $query = '
531                                                INSERT INTO ' . ECARD_TABLE .'
532                                                VALUES ( "'.$image_element['next_element_id'].'","'
533                                                                 .$_POST['votrenom'].'","'
534                                                                 .$_POST['sonnom'].'","'
535                                                                 .$_POST['votremail'].'","'
536                                                                 .$_POST['sonmail'].'","'
537                                                                 .$_POST['sujet'].'","'
538                                                                 .$_POST['message'].'",'
539                                                                 .$image_element['id'].',
540                                                                 now(),'
541                                                                 .(isset($_POST['ecard_activ']) ? $_POST['ecard_activ'] : $this->my_config['activ'])
542                                                                 .');';
543                                                // TO DO : add valid date (end date or duration) / add number (increment number) /
544
545                        if ($this->debug)                       echo $query."\n";
546                                                pwg_query($query);
547
548                                                // Complete the image_element array with Link for the ecard url to be added in the mail
549                                                set_make_full_url();
550                                                $chemin = embellish_url(get_absolute_root_url() . './index.php?/ecard/'.$image_element['next_element_id']);
551                                                $image_element['chemin'] = $chemin;
552                                                unset_make_full_url();
553        //                                      echo "chemin = ".$chemin."\n" ;
554
555                                                // Complete the image_element with the url to point to the image url
556                                                set_make_full_url();
557                                                $image_element['url_picture'] = duplicate_picture_url(
558                                                  array(
559                                                        'image_id' => $image_element['id'],
560                                                        'image_file' => $image_element['file']
561                                                  ),
562                                                  array('start')
563                                                );
564                                                unset_make_full_url();
565                                               
566
567                                                $sujetdumail = htmlspecialchars_decode($this->parse( $this->my_config['subject_link'], $_POST));
568                                               
569                                                switch($send_method)
570                                                {
571                                                case 0 : // text
572                                                        // Get the standard message (in admin param) and parse it with the informations
573                                                        $messagemail =  stripslashes(htmlspecialchars_decode($this->parse($this->my_config['message_link'], $_POST, $image_element)));
574
575                                                        $mail_arg=array('from' => $_POST['votremail'],
576                                                                                        'subject' => $sujetdumail,
577                                                                                        'content' => $messagemail,
578                                                                                        'content_format' => "text/plain",
579                                                                                        'email_format' => "text/html"
580                                                                                        );
581                                               
582                                                        break;
583                                                case 1 : // html
584                                                        $messagemailHTML =  stripslashes(htmlspecialchars_decode($this->parse($this->my_config['message_HTML'], $_POST, $image_element)));
585
586                                                        $mail_arg=array('from' => $_POST['votremail'],
587                                                                                        'subject' => $sujetdumail,
588                                                                                        'content' => $messagemailHTML,
589                                                                                        'content_format' => "text/html",
590                                                                                        'email_format' => "text/html"
591                                                                                        );
592                                                        if ($this->debug)               echo "messagemailHTML=".$messagemailHTML."\n";
593                                                        break;
594                                                }
595                                               
596                                                // Add the copy to expe if param.
597                                                if (isset($_POST['copy']))      // send copy to sender
598                                                        $mail_arg['Bcc'] = array((isset($_POST['votremail']) ? $_POST['votremail'] : $user['email']));
599                                               
600                                                // SEnd the mail
601                                                pwg_mail($_POST['sonmail'], $mail_arg);
602                                               
603                                        }
604                                        $template->set_filenames(array('ecard' =>  ECARD_ROOT.'/template/ecard.tpl'));
605                                        $template->concat('COMMENT_IMG', $template->parse('ecard', true));
606                                }
607                        }
608                }
609        }
610
611       
612        // Activation page administration
613        function ecard_admin_menu($menu)
614        {
615            array_push($menu,
616               array(
617                    'NAME' => ECARD_NAME,
618                    'URL' => get_admin_plugin_menu_link(ECARD_ADMIN_PATH.'admin.php')
619                ) 
620            );
621            return $menu;
622        }
623       
624       
625}
626
627?>
Note: See TracBrowser for help on using the repository browser.