source: extensions/ConcoursPhoto/include/Concours.class.php

Last change on this file was 32555, checked in by tiico, 3 years ago

Update podium view

File size: 80.6 KB
Line 
1<?php
2/*
3 * Plugin Name: ConcoursPhoto
4 * File :  Concours.class.php 
5 */
6 
7 
8include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
9
10global $user, $conf;
11
12class Concours
13{
14        var $concours_id = null;
15        var $concours_infos = array();
16       
17        // General configuration parameters
18        var $my_config = array();
19        var $user_groups = array();
20        var $debug = false;
21
22
23        /**
24         * Class constructor with concours id.
25         * Return NULL if not existing or create it
26         */
27        function __construct($concours_id = null, $force_creation = NULL) 
28        {
29                if ($concours_id !== null)
30                {               
31                        $this->concours_id = (int)$concours_id;
32                        $this->get_concours($concours_id);
33                }
34                // Load general parameters
35                $this->load_config();
36        }
37
38       
39        /**
40         * Load configuration from database
41         * Assign value to the variable $config
42         */
43        function load_config() {
44                $query = 'SELECT value FROM '.CONFIG_TABLE.' WHERE param="concoursphoto";';
45                $result = pwg_query($query);
46
47            if(isset($result)) {
48                        $row = pwg_db_fetch_row($result);
49                        if(is_string($row[0])) {
50                                $this->my_config = unserialize(($row[0]));
51                        }
52            }
53        if ($this->debug) 
54            foreach ($this->my_config as $key => $value) 
55                {
56                    echo "my_config[".$key."] = ".$value."\n";
57                }   
58            $this->load_default_config();
59        }
60       
61       
62        /**
63         * Load default configuration, initialize default values of params
64         */
65        private function load_default_config()
66        {
67            include CONCOURS_INC_PATH.'default_values.inc.php';
68            foreach ($concours_default_values as $key => $value) 
69                {
70                    if (!isset($this->my_config[$key]))         $this->my_config[$key] = $value;
71                }
72        }
73
74        // Save  general configuration to config_database
75        function save_config()
76        {
77                $query = '
78                  REPLACE INTO '.CONFIG_TABLE.'
79                  VALUES(
80                        \'concoursphoto\',
81                        \''.serialize($this->my_config).'\',
82                        \'Configuration Concours Photo\')
83                ;';
84
85                $result = pwg_query($query);
86
87                if($result) 
88                  return true;
89                else
90                  return false;
91        }
92       
93        /**
94         * Save the current configuration (ie the value of $config) to the database
95         */
96        function set_config() {
97                conf_update_param('concoursphoto', pwg_db_real_escape_string(serialize($this->my_config)));
98        }
99       
100       
101        // Retrieve user groups
102        function get_user_groups()
103        {
104                global $user;
105                $query = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . $user['id'] . ';';
106
107                $result = pwg_query($query);
108                while ($row = pwg_db_fetch_array($result))
109                {
110                  array_push($this->user_groups, $row['group_id']);
111                }
112
113        }
114
115        // create a concours and store it to db.
116        // return id for concours.
117        function create_concours()
118        {}
119
120        // Get informations array for  a concours id
121        function get_concours($concours_id = null)
122        {
123                if ($concours_id!== null or $this->concours_id !== null)
124                {
125                        $query = '
126                                SELECT *
127                                FROM ' . CONCOURS_TABLE .'
128                                WHERE id =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
129                                LIMIT 1
130                        ';
131
132                        $result = pwg_query($query);
133                        if ($result)
134                                $this->concours_infos = pwg_db_fetch_array($result);
135                }
136
137        }
138
139
140        // save informations on database for a concours_id
141        function save_concours($concours_id = null)
142        {
143                if ($concours_id!== null or $this->concours_id !== null)
144                {
145                                                       
146                        $query = "INSERT INTO " . CONCOURS_TABLE . "
147                                                ( `id`,
148                                                `create_date`,
149                                                `name`,
150                                                `descr`,
151                                                `begin_date`,
152                                                `end_date`,
153                                                `category`,
154                                                `groups`,
155                                                `method`,
156                                                `guest`,
157                                                `admin`
158                       
159                                                )
160                                        VALUES (".($concours_id !== NULL ? $concours_id : $this->concours_id).", now(),
161                                                        \"".$this->concours_infos['name']."\", \"".$this->concours_infos['descr']."\",
162                                                        \"".$this->concours_infos['begin_date']."\", \"".$this->concours_infos['end_date']."\",
163                                                        ".$this->concours_infos['category'].", ".$this->concours_infos['groups'].",
164                                                        ".$this->concours_infos['method'].", ".($this->concours_infos['guest'] ? "TRUE" : "FALSE").",
165                                                        ".($this->concours_infos['admin'] ? "TRUE" : "FALSE")."
166                                                        );";
167                        if (pwg_query($query) != null)
168                                return true;
169                        else
170                                return false;
171                }
172                else           
173                        return false;
174        }
175
176        // update informations on database for a concours_id
177        function update_concours($concours_id = null)
178        {
179                if ($concours_id!== null or $this->concours_id !== null)
180                {
181
182                        $query = "UPDATE " . CONCOURS_TABLE . "
183                                                SET
184                                                create_date = now(),
185                                                name = \"".$this->concours_infos['name']."\",
186                                                descr = \"".$this->concours_infos['descr']."\",
187                                                begin_date = \"".$this->concours_infos['begin_date']."\",
188                                                end_date = \"".$this->concours_infos['end_date']."\",
189                                                category = ".$this->concours_infos['category'].",
190                                                groups = ".$this->concours_infos['groups'].",
191                                                method = ".$this->concours_infos['method'].",
192                                                guest = ".($this->concours_infos['guest'] ? "TRUE" : "FALSE").",
193                                                admin = ".($this->concours_infos['admin'] ? "TRUE" : "FALSE").",
194                                                Podium_onCat = ".($this->concours_infos['Podium_onCat'] ? "TRUE" : "FALSE")."
195                                                WHERE id = ".($concours_id !== NULL ? $concours_id : $this->concours_id)."
196                                                ;";
197                        pwg_query($query);
198                        if (pwg_query($query) != null)
199                                return true;
200                        else
201                                return false;
202                }
203                else           
204                        return false;
205       
206        }
207       
208        // update field on database for a concours_id
209        function update_concoursfield($field_id, $concours_id = null, $field_value = null)
210        {
211                if ($concours_id!== null or $this->concours_id !== null)
212                {
213
214                        $query = "UPDATE " . CONCOURS_TABLE . "
215                                                SET
216                                                " . $field_id." = ". ($field_value != NULL ? $field_value : $this->concours_infos[$field_id] ) . "
217                                               
218                                                WHERE id = ".($concours_id !== NULL ? $concours_id : $this->concours_id)."
219                                                ;";
220                        pwg_query($query);
221                        if (pwg_query($query) != null)
222                                return true;
223                        else
224                                return false;
225                }
226                else           
227                        return false;
228       
229        }
230
231        // delete concours from db (and all sub informations such as details, vote and result
232        function delete_concours($concours_id = null)
233        {
234                if ($concours_id!== null or $this->concours_id !== null)
235                {
236               
237                        $query = '
238                                DELETE
239                                FROM ' . CONCOURS_RESULT_TABLE .'
240                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
241                                ';
242                        pwg_query($query);
243                        $query = '
244                                DELETE
245                                FROM ' . CONCOURS_DATA_TABLE .'
246                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
247                                ';
248                        pwg_query($query);
249                        $query = '
250                                DELETE
251                                FROM ' . CONCOURS_DETAIL_TABLE .'
252                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
253                                ';
254                        pwg_query($query);
255                        $query = '
256                                DELETE
257                                FROM ' . CONCOURS_TABLE .'
258                                WHERE id =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
259                                ';
260                        pwg_query($query);
261                }
262                else
263                        return false;
264               
265        }
266
267       
268        // delete all closed concours from db
269        function delete_allclosed_concours()
270        {
271                $concours_list=array();
272                $query = '
273                        SELECT id
274                        FROM ' . CONCOURS_TABLE .'
275                        WHERE time_to_sec(TIMEDIFF(now(), end_date)) > 0
276                        AND  id>0;';
277
278                $result = pwg_query($query);
279                while ($row = pwg_db_fetch_assoc($result))
280                {
281                        $this->delete_concours($row['id']);
282                }
283        }
284
285                       
286        // today's date is between open and close date of concours?
287        function is_active($concours_id = NULL)
288        {
289                if ($concours_id!== null or $this->concours_id !== null)
290                {
291                        $query = '
292                                SELECT id
293                                FROM ' . CONCOURS_TABLE .'
294                                WHERE id =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
295                                AND time_to_sec(TIMEDIFF(begin_date,now())) < 0
296                                AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
297                                ';
298
299                        $result = pwg_query($query);
300                        if ($result != NULL)
301                                return true;
302                        else
303                                return false;
304                }
305                else
306                        return NULL;
307        }
308
309        // today's date is not between open and close date of concours?
310        function is_closed($concours_id = NULL)
311        {
312                if ($concours_id!== null or $this->concours_id !== null)
313                {
314                        $query = '
315                                SELECT id
316                                FROM ' . CONCOURS_TABLE .'
317                                WHERE id =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
318                                AND time_to_sec(TIMEDIFF(now(), end_date)) > 0
319                                ';
320
321                        $result = pwg_query($query);
322                        if ($result != NULL)
323                                return true;
324                        else
325                                return false;
326                }
327                else
328                        return NULL;
329        }
330
331        // Get high value of concours (max score for each criterias)
332        function get_MaxScore_concours($concours_id = null)
333        {
334                $max = 0;
335                $query = '
336                        SELECT criteria_id, max_value, ponderation, uppercriteria
337                        FROM ' . CONCOURS_DETAIL_TABLE .'
338                        WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
339                        ORDER BY criteria_id
340                        ';
341                $result = pwg_query($query);
342                while ($row = pwg_db_fetch_array($result))
343                {
344                        if ($row['uppercriteria'] != NULL || !$this->is_criterias_contains_sub($row['criteria_id'])) // subcriteria or uppercriteria without sub
345                                $max += $row['max_value']*$row['ponderation'];
346                }
347                return $max;
348
349
350        }       
351       
352        // Get criterias that are stored on db for default mode (concours_id = 0)
353        function get_default_criterias()
354        {
355                $criterias = $this->get_criterias_list(0);
356                $query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
357                                        FROM ' . CONCOURS_DETAIL_TABLE . ' ;';
358                list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
359
360                foreach ($criterias as $criteria)
361                {               
362                       
363                        $query = 'INSERT INTO '.CONCOURS_DETAIL_TABLE.'
364                                                (id, id_concours, criteria_id, name, descr, min_value, max_value, ponderation, uppercriteria)'
365                                                .'VALUES ('.$next_element_id.', '.$this->concours_id.', '
366                                                .$criteria['criteria_id'].', "'.$criteria['name'].'", "'
367                                                .$criteria['descr'].'", '.$criteria['min_value'].', '
368                                                .$criteria['max_value'].', '.$criteria['ponderation'].', '
369                                                .($criteria['uppercriteria'] ? $criteria['uppercriteria'] : 'NULL').')
370                                                ;';
371                       
372                                $result = pwg_query($query);
373
374                        $next_element_id = $next_element_id +1;
375                }
376        }
377
378        // Get criterias from a concours
379        function get_criterias_list($concours_id = NULL)
380        {
381                $criteria_list = array();
382                if ($concours_id!== null or $this->concours_id !== null)
383                {
384                        $query = '
385                                SELECT *
386                                FROM ' . CONCOURS_DETAIL_TABLE .'
387                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
388                                ORDER BY criteria_id
389                                ';
390                        $result = pwg_query($query);
391                        while ($row = pwg_db_fetch_array($result))
392                        {
393                                array_push($criteria_list, $row);
394                        }
395                        return $criteria_list;
396                }
397                else
398                        return $criteria_list;
399        }
400
401        // Get list of the fist level criterias
402        function get_firstlevel_criterias($concours_id = NULL)
403        {
404                $criteria_list = array();
405                if ($concours_id!== null or $this->concours_id !== null)
406                {
407                        $query = '
408                                SELECT *
409                                FROM ' . CONCOURS_DETAIL_TABLE .'
410                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
411                                AND uppercriteria IS NULL
412                                ORDER BY criteria_id
413                                ';
414                        $result = pwg_query($query);
415                       
416                        while ($row = pwg_db_fetch_array($result))
417                                array_push($criteria_list, $row);
418                        return $criteria_list;
419                }
420                else
421                        return $criteria_list;
422        }
423
424        // check if a criteria contains subcriterias
425        function is_criterias_contains_sub($criteria_id, $concours_id = NULL)
426        {
427                if ($concours_id!== null or $this->concours_id !== null)
428                {
429                        $query = '
430                                SELECT criteria_id
431                                FROM ' . CONCOURS_DETAIL_TABLE .'
432                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
433                                AND uppercriteria = '.$criteria_id.'
434                                ';
435                        $result = pwg_query($query);
436                        if(pwg_db_fetch_array($result))
437                                return true;
438                        else
439                                return false;
440                }
441                return NULL;
442        }
443       
444       
445        // Get list of subcriterias from a criteria_id
446        function get_subcriterias($criteria_id, $concours_id = NULL)
447        {
448                $criteria_list = array();
449                if ($concours_id!== null or $this->concours_id !== null)
450                {
451                        $query = '
452                                SELECT *
453                                FROM ' . CONCOURS_DETAIL_TABLE .'
454                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
455                                AND uppercriteria = '.$criteria_id.'
456                                ORDER BY criteria_id
457                                ';
458                        $result = pwg_query($query);
459                        while ($row = pwg_db_fetch_array($result))
460                        {
461                                array_push($criteria_list, $row);
462                        }
463                        return $criteria_list;
464                }
465                else
466                        return $criteria_list;
467        }
468       
469        // Get a detail from a criteria
470        function get_criteria($criteria_id, $concours_id = NULL)
471        {
472                $criteria = array();
473
474                if ($concours_id!== null or $this->concours_id !== null)
475                {
476                        $query = '
477                                SELECT *
478                                FROM ' . CONCOURS_DETAIL_TABLE .'
479                                WHERE id_concours = '. ($concours_id !== null ? $concours_id : $this->concours_id ) . '
480                                AND criteria_id =' . $criteria_id . '
481                                ';
482                        $result = pwg_query($query);
483                       
484            $criteria = pwg_db_fetch_array($result);
485                }
486                return $criteria;
487       
488        }
489
490        // Get a detail from a criteria
491        function get_criteria_by_id($id)
492        {
493                $criteria = array();
494
495                $query = '
496                        SELECT *
497                        FROM ' . CONCOURS_DETAIL_TABLE .'
498                        WHERE id =' . $id . '
499                        ';
500                $result = pwg_query($query);
501               
502                $criteria = pwg_db_fetch_array($result);
503                return $criteria;
504       
505        }
506
507        // Add a criteria to a concours
508        // Datas is an array and contains all infos.
509        // Return the criteria id
510        function add_criteria($datas, $concours_id = NULL)
511        {
512                // determines the criteria_id
513                if ($concours_id!== null or $this->concours_id !== null)
514                {
515                        $query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
516                                                FROM ' . CONCOURS_DETAIL_TABLE . ' ;';
517                        list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
518
519                        $query = 'SELECT IF(MAX(criteria_id)+1 IS NULL, 1, MAX(criteria_id)+1) AS next_criteria_id
520                                                FROM ' . CONCOURS_DETAIL_TABLE . '
521                                          WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ) . ' ;';
522                        list($next_criteria_id) = pwg_db_fetch_array(pwg_query($query));
523                       
524                        $query = '
525                        INSERT INTO ' . CONCOURS_DETAIL_TABLE .'
526                                (`id`,
527                                `id_concours`,
528                                `criteria_id`,
529                                `name`,
530                                `descr`,
531                                `min_value`,
532                                `max_value`,
533                                `ponderation`,
534                                `uppercriteria`)
535                                VALUES (
536                                '.$next_element_id.', '.($concours_id !== null ? $concours_id : $this->concours_id ).',
537                                '.$next_criteria_id.', "'.$datas['name'].'", "'.$datas['descr'].'", '.$datas['min_value'].'
538                                , '.$datas['max_value'].', '.$datas['ponderation'].'
539                                , '.($datas['uppercriteria'] ? $datas['uppercriteria'] : 'NULL').'
540                                );';
541
542                        pwg_query($query);
543                        if ($this->debug) echo $query."\n";
544       
545                }
546        }
547       
548        // Update a criteria to a concours
549        // Datas is an array and contains all infos.
550        function update_criteria($datas, $concours_id = NULL)
551        {
552                // determines the criteria_id
553                if ($concours_id!== null or $this->concours_id !== null)
554                {
555                        $query = '
556                                UPDATE ' . CONCOURS_DETAIL_TABLE .'
557                                SET
558                                name = "'.$datas['name'].'",
559                                descr = "'.$datas['descr'].'",
560                                min_value = '.$datas['min_value'].',
561                                max_value = '.$datas['max_value'].',
562                                '.($datas['uppercriteria'] == false ? '' : 'uppercriteria = '.($datas['uppercriteria'] ? $datas['uppercriteria'].',' : 'NULL ,')).'
563                                ponderation = '.$datas['ponderation'].'
564                                WHERE id = '.$datas['id'].';';
565
566                        pwg_query($query);
567                }               
568        }
569       
570
571        // Delete a criteria from a concours
572        function delete_criteria($criteria_id, $concours_id = NULL)
573        {
574                if ($concours_id!== null or $this->concours_id !== null)
575                {
576               
577                        $query = '
578                                DELETE
579                                FROM ' . CONCOURS_DETAIL_TABLE .'
580                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
581                                AND criteria_id = '.$criteria_id.'
582                                ';
583                        $result = pwg_query($query);
584                       
585                        if($result)
586                                return true;
587                        else
588                                return false;
589                }
590                else
591                        return null;
592
593        }
594       
595        // Delete a criteria (with id) from a concours
596        function delete_criteria_by_id($id)
597        {
598       
599                $query = '
600                        DELETE
601                        FROM ' . CONCOURS_DETAIL_TABLE .'
602                        WHERE id =' . $id . '
603                        ';
604                $result = pwg_query($query);
605
606        }       
607
608        // check if a result is already present in the database
609        function is_result_present($concours_id = null)
610        {
611                // recover all img_id from the category
612                $query = 'SELECT DISTINCT(id_concours)'
613                .' FROM ' .CONCOURS_RESULT_TABLE
614                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ).';';
615               
616                $result = pwg_query($query);
617                // For each images
618                if (pwg_db_fetch_array($result))
619                        return true;
620                else
621                        return false;
622       
623        }
624       
625       
626       
627// TESTTEST
628        // function to return the number of images for a concours
629        function nb_img_by_concours($concours_id = NULL)
630        {
631
632               
633                // nb of users who vote for each image (for a selected concours
634                $query = 'SELECT count(img.id) AS NBIMG '
635                                .' FROM ' . IMAGES_TABLE.' AS img'
636                                .' INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON img.id = ic.image_id'
637                                .' INNER JOIN '.CATEGORIES_TABLE.' AS cat ON ic.category_id = cat.id'
638                                .' INNER JOIN '.CONCOURS_TABLE.' AS conc ON conc.category = cat.id'
639                                        .' WHERE conc.id = '.($concours_id !== null ? $concours_id : $this->concours_id )
640                                .';';
641                               
642                $result = pwg_query($query);
643                if ($row = pwg_db_fetch_array($result))
644                {
645                        return $row['NBIMG'];
646                }
647                               
648                return 0;
649        }
650
651       
652        // function to return the number of votes for a concours by images
653        function nb_votes_by_img($concours_id = NULL)
654        {
655               
656                // nb of users who vote for each image (for a selected concours
657                $query = 'SELECT img_id, COUNT(DISTINCT user_id) AS NBVOTE FROM ' . CONCOURS_DATA_TABLE 
658                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
659        .' AND ipguest IS NULL'
660                .' GROUP BY img_id '
661                .';';
662                               
663                $result = pwg_query($query);
664                $nbvotes = array();
665                while ($row = pwg_db_fetch_array($result))
666                {
667                        $nbvotes[$row['img_id']] = $row['NBVOTE'];
668                }
669       
670        // Add guest infos
671        $query = 'SELECT img_id, COUNT(DISTINCT ipguest) AS NBVOTE FROM ' . CONCOURS_DATA_TABLE 
672        .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
673        .' AND ipguest IS NOT NULL'
674        .' GROUP BY img_id '
675        .';';
676               
677        $result = pwg_query($query);
678        while ($row = pwg_db_fetch_array($result))
679       
680            if (!isset($nbvotes[$row['img_id']]))
681                $nbvotes[$row['img_id']] = $row['NBVOTE'];
682            else
683                $nbvotes[$row['img_id']] += $row['NBVOTE'];
684                       
685                return $nbvotes;
686        }
687
688       
689       
690        // Get All user that are vote  for guest who have vote (IP Stores in db) in a concours
691        function get_user_list($concours_id = NULL)
692        {
693                global $conf;
694        $userid = array();
695                if ($concours_id!== null or $this->concours_id !== null)
696                {
697                        $query = '
698                                SELECT distinct(user_id)
699                                FROM ' . CONCOURS_DATA_TABLE .'
700                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id ) . '
701                AND ipguest IS  NULL
702                                AND user_id !='.$conf['guest_id']
703
704                                .' ORDER BY user_id
705                                ';
706                        $result = pwg_query($query);
707                        while ($row = pwg_db_fetch_array($result))
708                        {
709                                array_push($userid, $row['user_id']);
710                        }
711                }
712                return $userid;
713        }
714       
715       
716        // Get All iaddr for guest who have vote (IP Stores in db) in a concours
717        function get_guest_list($concours_id = NULL)
718        {
719                global $conf;
720        $ipguest = array();
721                if ($concours_id!== null or $this->concours_id !== null)
722                {
723                        $query = '
724                                SELECT distinct(ipguest)
725                                FROM ' . CONCOURS_DATA_TABLE .'
726                                WHERE id_concours =' . ($concours_id !== null ? $concours_id : $this->concours_id )
727                .' AND user_id = '.$conf['guest_id']
728                .' AND ipguest IS NOT NULL
729                                ORDER BY ipguest
730                                ';
731                        $result = pwg_query($query);
732                        while ($row = pwg_db_fetch_array($result))
733                        {
734                                array_push($ipguest, $row['ipguest']);
735                        }
736            if ($this->debug)
737            {
738                foreach ($ipguest as $ip)
739                    echo "IP=".$ip."\n";
740            }
741
742                        return $ipguest;
743                }
744                else
745                        return $ipguest;
746        }
747   
748       
749        // After concours is completed (closed date is passed), generate the result and store it to DB
750        function create_result($concours_id = NULL)
751        {
752        global $conf;
753                // var which contains id=img_id and val =global note
754                $global_note = array();
755                // FOR MODERATION
756                // var which contains id=user_id and val =global note
757                $vote_by_user = array();
758                $amplitiudeMINmax = 999; // MIN of all max score (for each users)
759                $amplitiudeMAXmin = -999; // MIN of all max score (for each users)
760                $REFaverage = 0;        // reference average (average between amplitiudeMINmax and amplitiudeMAXmin)
761                $global_note_mod1 = array();
762                $global_note_mod2 = array();
763               
764                if ($concours_id!== null or $this->concours_id !== null)
765                {
766                        // only for closed concours and not already result generated
767                        if ($this->is_closed($concours_id) AND ! $this->is_result_present($concours_id))
768                        {
769                       
770                                // array with the number of vote by image for the concours. Needed for the moyenne
771                                $nbvotes = $this->nb_votes_by_img($concours_id);
772                               
773               
774                                $user_id = array();
775                                // vars not initialized
776                                if ($this->concours_infos == array())
777                                        $this->get_concours();
778                                $category = $this->concours_infos['category'];
779                               
780                                // Get all user_id from a concours
781                                $query = 'SELECT DISTINCT user_id'
782                                .' FROM ' .CONCOURS_DATA_TABLE
783                                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
784                .' AND user_id <> '.$conf['guest_id']
785                                .';';
786                                $result = pwg_query($query);
787
788                                while ($row = pwg_db_fetch_array($result))
789                                        array_push($user_id, $row['user_id']);
790
791                // Add guest info is present
792                $ipguest = array();
793                if ($concours_id!== null or $this->concours_id !== null)
794                                {
795                                        if ($this->debug)
796                                                echo "Check IPGUEST";
797                    $ipguest = $this->get_guest_list(($concours_id !== null ? $concours_id : $this->concours_id ));
798                                }
799
800                               
801                                // recover all img_id from the category
802                                $query = 'SELECT DISTINCT(image_id)'
803                                .' FROM ' .IMAGE_CATEGORY_TABLE
804                                .' WHERE category_id = '.$category.';';
805                               
806                                $nb_image_concours = 0;
807                                $result = pwg_query($query);
808                                // For each images
809                                while ($row = pwg_db_fetch_array($result))
810                                {
811                                        $nb_image_concours++;
812               
813                                        foreach ($user_id as $i => $userid)
814                                        {
815                                                $img_note_user = $this->get_img_globalnote_user($row['image_id'], null, $userid);
816                                               
817                                                if (!isset($global_note[$row['image_id']]))
818                                                        $global_note[$row['image_id']] = 0;
819                                        // FOR MODERATION
820                                        // store the nb of vote for each user
821                                                if ($img_note_user >= 0) // user has made a vote
822                                                {
823                                                        if (!isset($vote_by_user[$userid]['nbvote']))
824                                                                $vote_by_user[$userid]['nbvote'] = 0;
825                                                       
826                                                        $vote_by_user[$userid]['nbvote'] ++;    // update vote counter
827                                               
828                                                        $global_note[$row['image_id']] +=  $img_note_user       ;               
829                                               
830
831                                                // FOR MODERATION
832                                                        // store the total of note for the same user
833                                                        if (!isset($vote_by_user[$userid]['totalvote']))
834                                                                $vote_by_user[$userid]['totalvote'] = 0;
835                                                        $vote_by_user[$userid]['totalvote'] +=  $img_note_user;
836                                                        // FOR MODERATION
837                                                        // store min/max for each user
838                                                        if (!isset($vote_by_user[$userid]['min']))      $vote_by_user[$userid]['min'] = 999;
839                                                        if (!isset($vote_by_user[$userid]['max']))      $vote_by_user[$userid]['max'] = 0;
840                                                       
841                                                       
842                                                        if ($vote_by_user[$userid]['min'] > $img_note_user) $vote_by_user[$userid]['min'] = $img_note_user;
843                                                        if ($vote_by_user[$userid]['max'] < $img_note_user) $vote_by_user[$userid]['max'] = $img_note_user;
844                                                }                                               
845                                       
846                                        }
847                    // Add guest scores if present
848                                        foreach ($ipguest as $i => $userid)
849                                        {
850                                               
851                                                $img_note_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid); // $userid contains the ip address for the guest!
852                                                if (!isset($global_note[$row['image_id']]))
853                                                        $global_note[$row['image_id']] = 0;
854
855                                        // FOR MODERATION
856                                        // store the nb of vote for each guest (with ipaddr)
857                                                if ($img_note_user >= 0) // user has made a vote
858                                                {
859                                                        if (!isset($vote_by_user[$userid]['nbvote']))
860                                                                $vote_by_user[$userid]['nbvote'] = 0;
861                                                       
862                                                        $vote_by_user[$userid]['nbvote'] ++;    // update vote counter
863                                               
864                                                        $global_note[$row['image_id']] +=  $img_note_user       ;               
865                                               
866
867                                                // FOR MODERATION
868                                                        // store the total of note for the same user
869                                                        if (!isset($vote_by_user[$userid]['totalvote']))
870                                                                $vote_by_user[$userid]['totalvote'] = 0;
871                                                        $vote_by_user[$userid]['totalvote'] +=  $img_note_user;
872                                                        // FOR MODERATION
873                                                        // store min/max for each user
874                                                        if (!isset($vote_by_user[$userid]['min']))      $vote_by_user[$userid]['min'] = 999;
875                                                        if (!isset($vote_by_user[$userid]['max']))      $vote_by_user[$userid]['max'] = 0;
876                                                       
877                                                       
878                                                        if ($vote_by_user[$userid]['min'] > $img_note_user) $vote_by_user[$userid]['min'] = $img_note_user;
879                                                        if ($vote_by_user[$userid]['max'] < $img_note_user) $vote_by_user[$userid]['max'] = $img_note_user;
880                                                }                                               
881
882                                        }
883                                }
884
885                                // FOR MODERATION
886                                // calcul the average by user and min/max global
887                                foreach ($user_id as $i => $userid)
888                                {
889                                        $vote_by_user[$userid]['average'] = $vote_by_user[$userid]['totalvote']/$vote_by_user[$userid]['nbvote'];
890                                        $vote_by_user[$userid]['lowerAmp'] = $vote_by_user[$userid]['min'];
891                                        // calcul the max value of the concours (for the moderation)
892                                        $vote_by_user[$userid]['upperAmp'] = $this->get_MaxScore_concours() - $vote_by_user[$userid]['max'];
893                                       
894                                        $vote_by_user[$userid]['minLevel'] = $vote_by_user[$userid]['average'] - $vote_by_user[$userid]['lowerAmp'];
895                                        $vote_by_user[$userid]['maxLevel'] = $vote_by_user[$userid]['average'] + $vote_by_user[$userid]['upperAmp'];
896                                        if ($amplitiudeMINmax > $vote_by_user[$userid]['maxLevel']) $amplitiudeMINmax = $vote_by_user[$userid]['maxLevel'];
897                                        if ($amplitiudeMAXmin < $vote_by_user[$userid]['minLevel']) $amplitiudeMAXmin = $vote_by_user[$userid]['minLevel'];                             
898                                }
899
900                                // calcul the average by guest and min/max global
901                                foreach ($ipguest as $i => $userid)
902                                {
903                                        $vote_by_user[$userid]['average'] = $vote_by_user[$userid]['totalvote']/$vote_by_user[$userid]['nbvote'];
904                                        $vote_by_user[$userid]['lowerAmp'] = $vote_by_user[$userid]['min'];
905                                        // calcul the max value of the concours (for the moderation)
906                                        $vote_by_user[$userid]['upperAmp'] = $this->get_MaxScore_concours() - $vote_by_user[$userid]['max'];
907                                       
908                                        $vote_by_user[$userid]['minLevel'] = $vote_by_user[$userid]['average'] - $vote_by_user[$userid]['lowerAmp'];
909                                        $vote_by_user[$userid]['maxLevel'] = $vote_by_user[$userid]['average'] + $vote_by_user[$userid]['upperAmp'];
910                                        if ($amplitiudeMINmax > $vote_by_user[$userid]['maxLevel']) $amplitiudeMINmax = $vote_by_user[$userid]['maxLevel'];
911                                        if ($amplitiudeMAXmin < $vote_by_user[$userid]['minLevel']) $amplitiudeMAXmin = $vote_by_user[$userid]['minLevel'];                             
912
913                                }
914
915
916                                // FOR MODERATION
917                                // calcul the reference average
918                                $calcultemp = (int)($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5;
919                                if ((int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5) > $amplitiudeMAXmin)
920                                {
921                                        if ((int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5) < $amplitiudeMINmax)
922                                                $REFaverage = (int)(($amplitiudeMINmax+$amplitiudeMAXmin)/2+0.5);
923                                        else
924                                                $REFaverage = $amplitiudeMINmax;
925                                }
926                                else
927                                        $REFaverage = $amplitiudeMAXmin;
928                               
929                                       
930                                // FOR MODERATION
931                                // calcul the moderation scopr for each users
932                                foreach ($user_id as $i => $userid)
933                                        $vote_by_user[$userid]['moderation'] = $REFaverage - $vote_by_user[$userid]['average'];
934
935                                // FOR MODERATION
936                                // calcul the moderation scopr for each guest ($ipguest)
937                                foreach ($ipguest as $i => $userid)
938                                        $vote_by_user[$userid]['moderation'] = $REFaverage - $vote_by_user[$userid]['average'];
939                                       
940                                // FOR MODERATION
941                                // need to parse again image for new calcul with moderation
942                                // moderation 1 => For each photo without note (user = author or user != author but no vote) add each user avaerage to the total of note and calcul the average
943                                // moderation 2 => For each photo with note, adapt/change all the value with the moderation value : user note + moderation.
944
945                                // parse again all img_id from the category
946                                $query = 'SELECT DISTINCT(image_id)'
947                                .' FROM ' .IMAGE_CATEGORY_TABLE
948                                .' WHERE category_id = '.$category.';';
949                               
950                                $result = pwg_query($query);
951                                // For each images
952                                while ($row = pwg_db_fetch_array($result))
953                                {
954                                        // for each user
955                                        foreach ($user_id as $i => $userid)
956                                        {
957                                                if (!isset($global_note_mod1[$row['image_id']]))
958                                                        $global_note_mod1[$row['image_id']] = 0;
959                                                $globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, $userid, null, 1, $vote_by_user[$userid]['average']);
960
961                                                $global_note_mod1[$row['image_id']] += ($globalnote_user >= 0 ? $globalnote_user : 0)   ;
962
963                                                if (!isset($global_note_mod2[$row['image_id']]))
964                                                        $global_note_mod2[$row['image_id']] = 0;
965                                                $globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, $userid, null, 2, $vote_by_user[$userid]['moderation']);
966
967                                                $global_note_mod2[$row['image_id']] +=  ($globalnote_user >= 0 ? $globalnote_user : 0)  ;               
968                                        }
969                                       
970                                        // for each guest
971                                        foreach ($ipguest as $i => $userid)
972                                        {
973                                                if (!isset($global_note_mod1[$row['image_id']]))
974                                                        $global_note_mod1[$row['image_id']] = 0;
975                                                $globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid, 1, $vote_by_user[$userid]['average']); // userid contains the ip addr for the guest
976
977                                                $global_note_mod1[$row['image_id']] += ($globalnote_user >= 0 ? $globalnote_user : 0)   ;
978
979                                                if (!isset($global_note_mod2[$row['image_id']]))
980                                                        $global_note_mod2[$row['image_id']] = 0;
981                                                $globalnote_user = $this->get_img_globalnote_user($row['image_id'], null, null, $userid, 2, $vote_by_user[$userid]['moderation']);
982
983                                                $global_note_mod2[$row['image_id']] +=  ($globalnote_user >= 0 ? $globalnote_user : 0)  ;               
984                                        }
985
986                                       
987                                }
988                                       
989                               
990                                // update database and store result into RESULT table
991                                // note = global note
992                                $IMGmoyenne = 0;
993                                $IMGmoyenneModeration1 = 0;
994                                $IMGmoyenneModeration2 = 0;
995                               
996                                foreach ($global_note as $id => $val)
997                                // id contains the image id
998                                {
999                                        $IMGmoyenne = (isset($nbvotes[$id]) && $nbvotes[$id] != 0 ? $val/$nbvotes[$id] : 0);
1000                                        // Moderation
1001
1002                                        $IMGmoyenneModeration1 = ($nb_image_concours != 0 ? $global_note_mod1[$id]/$this->nb_user_by_concours() : 0);   // all photos have note
1003                                        $IMGmoyenneModeration2 = (isset($nbvotes[$id]) && $nbvotes[$id] != 0 ? $global_note_mod2[$id]/$nbvotes[$id] : 0);       // only voted photos are used
1004                                       
1005                                        $query = 'INSERT INTO  ' . CONCOURS_RESULT_TABLE .'(`id_concours`, `img_id`, `date` , `note`, `moyenne`,
1006                                        `moderation1`, `moderation2`,
1007                                        `nbvotant` )
1008                                                        VALUES ('.($concours_id !== null ? $concours_id : $this->concours_id )
1009                                                                         .', '.$id 
1010                                                                         .', now() '
1011                                                                         .', '.$val
1012                                                                         .', '.$IMGmoyenne
1013                                                                         .', '.$IMGmoyenneModeration1
1014                                                                         .', '.$IMGmoyenneModeration2
1015                                                                         .', '.(isset($nbvotes[$id]) ? $nbvotes[$id] : 0)
1016                                                                         .');';
1017                                $result = pwg_query($query);     
1018                                       
1019                                }
1020                        }
1021                        else
1022                                return false;
1023                }
1024                else
1025                        return false;
1026        }
1027       
1028       
1029        // Get array with nb of vote for each user of a concours_id
1030        function nb_user_by_concours($concours_id = NULL)
1031        {
1032                $nbusertotal = 0;
1033                // user
1034                $query = 'SELECT count(distinct(user_id)) as nb_user FROM ' . CONCOURS_DATA_TABLE .'
1035                                WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id).'
1036                                AND ipguest IS NULL
1037                          ;';
1038                $result = pwg_query($query);
1039                if ($result)
1040                {
1041                        $row = pwg_db_fetch_array($result);
1042                        $nbusertotal += $row['nb_user'];
1043                }
1044                // guest
1045                $query = 'SELECT count(distinct(ipguest)) as nb_user FROM ' . CONCOURS_DATA_TABLE .'
1046                                WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id).'
1047                                AND ipguest IS NOT NULL
1048                          ;';
1049                $result = pwg_query($query);
1050                if ($result)
1051                {
1052                        $row = pwg_db_fetch_array($result);
1053                        $nbusertotal +=  $row['nb_user'];
1054                }
1055                return $nbusertotal;
1056               
1057        }
1058       
1059       
1060        // Check if an image's author OR addebBy is the same as the actual user
1061        // depending the config param
1062        function check_img_user($img_id)
1063        {
1064                global $user;
1065
1066
1067                $query = '
1068                        SELECT id,author, added_by
1069                        FROM ' . IMAGES_TABLE .'
1070                        WHERE id =' . $img_id . '
1071                        ';
1072
1073                $result = pwg_query($query);
1074if ($this->debug) echo $query."\n<br>";
1075                if ($result)
1076                {
1077                        $row = pwg_db_fetch_array($result);
1078                        $authorid = get_userid($row['author']);
1079                        $addedbyid = $row['added_by'];
1080
1081
1082/*
1083echo "img ID=".$row['id']."<br>";       
1084echo ">>>auteur=".$row['author']."<br>";       
1085echo ">>>authorid=".$authorid."<br>";
1086echo ">>>addedbyid=".$addedbyid."<br>"; 
1087echo ">>>Type_compare=".$this->my_config['author_vote_available'].'<br>';
1088*/
1089
1090
1091                        switch ($this->my_config['author_vote_available'])
1092                        {
1093                       
1094                                case 0 : // no check (allow to vote for all photos)
1095                                        return false;
1096                                       
1097                                case 1 : // check between author and user
1098                                        if ($authorid)  // Author name present as username
1099                                        {
1100                                                if ($authorid == $user['id'])
1101                                                        return true;
1102                                                else
1103                                                        return false;
1104                                        }
1105                                        else
1106                                        {
1107                                                // check if author name = user name
1108                                                $AuthorArray = strip_punctuation2($row['author']);
1109                                                $UserArray = strip_punctuation2($user['username']);
1110                                                // Patch if author is empty
1111                                                if (empty($AuthorArray))
1112                                                        return false;
1113                               
1114                                                if (count(array_intersect($AuthorArray, $UserArray)) == count ($AuthorArray)) // found                         
1115                                                        return true;
1116                                                else
1117                                                        return false;
1118                                        }
1119       
1120                                       
1121                                case 2 : // check between author and user
1122                                        if (isset($addedbyid) AND $addedbyid == $user['id'])
1123                                                return true;
1124                                        else
1125                                                return false;
1126                                case 3 : // check between author OR addedby and user
1127                                        // Check Author
1128                                        if ($authorid AND $authorid == $user['id'])     // Author name present as username
1129                                        {
1130//                                              echo " > > > Auteur OK1 <br>";
1131                                                        return true;
1132                                        }
1133                                        else
1134                                        {
1135                                                // check if author name = user name
1136                                                $AuthorArray = strip_punctuation2($row['author']);
1137                                                $UserArray = strip_punctuation2($user['username']);                                                             
1138                                                if (!empty($AuthorArray) AND (count(array_intersect($AuthorArray, $UserArray)) == count ($AuthorArray))) // found                               
1139                                                {
1140//                                                      echo " > > > Auteur OK2 <br>";
1141                                                        return true;
1142                                                }
1143                                        }                       
1144                                        // check addebBy
1145                                        if (isset($addedbyid) AND $addedbyid == $user['id'])
1146                                        {
1147//                                              echo " > > >ADDED OK <br>";
1148                                                return true;
1149                                        }
1150//                                      echo " > > > FASLSE <br>";
1151                                        return false;
1152
1153                                default :
1154//                                      echo " > > > FASLSE <br>";
1155                                        return false;
1156                               
1157                        }
1158
1159                }
1160                return false;
1161        }
1162       
1163
1164        // Add tpl to picture.php page to display concours informations and vote
1165        function display_concours_to_picture()
1166        {
1167                // Step0 : if user = guest, check the concours param and store ip address to user name.
1168                // Step1 : concours is defined to this category AND concours is open AND user is authorized to access to this category (thru group)
1169                // Step1 bis : dont show concours if check author or added_by id is the samie as used_id (depending the param)
1170                // Step 2 : Recover stored informations in db for this user
1171                // Step 3 : Complete tpl information
1172                // Step 4 : concat tpl
1173               
1174                global $page, $user, $template, $conf;
1175
1176                // Get user group.
1177                $this->get_user_groups();
1178
1179                $concours = array();
1180
1181        // STEP 0
1182                $user['ipguest'] = null;
1183
1184                // Check if the user is a guest only
1185                if (is_a_guest())
1186                {
1187                        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
1188                                $IP = $_SERVER['HTTP_X_FORWARDED_FOR']; 
1189                        elseif(isset($_SERVER['HTTP_CLIENT_IP']))   
1190                                $IP = $_SERVER['HTTP_CLIENT_IP'];   
1191                        else
1192                                $IP = $_SERVER['REMOTE_ADDR']; 
1193                                 
1194                        // store ip
1195                        $user['ipguest'] = $IP;
1196                }
1197       
1198       
1199                // disable author name  on image which are present in a concours.
1200                // check the categories where the current image is present and disable the author name
1201                if (isset($this->my_config['mask_author']) && $this->my_config['mask_author'] == true)
1202                {
1203                        // Get all categories where the current image is present
1204                        $query = '
1205                        SELECT category_id,uppercats,commentable,global_rank
1206                          FROM '.IMAGE_CATEGORY_TABLE.'
1207                                INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
1208                          WHERE image_id = '.$page['image_id'].'
1209                          ;';
1210                        $result = pwg_query($query);
1211                        $related_categories = array();
1212                        while ($row = pwg_db_fetch_array($result))
1213                        {
1214                          array_push($related_categories, $row['category_id']);
1215                        }
1216                        //
1217            //echo related_categories;
1218            if (count($related_categories))
1219            {
1220                // Request for all concours prepared & actived on each categories
1221                $query = '
1222                    SELECT *
1223                    FROM ' . CONCOURS_TABLE .'
1224                    WHERE category IN ('.implode(',', $related_categories).')
1225                    AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
1226                ';
1227                $result = pwg_query($query);
1228                // If one or more concours are found, the author name is masked
1229                if ($result && pwg_db_fetch_array($result))
1230                    $template->assign('INFO_AUTHOR',l10n('concours_img_author'));
1231            }
1232                }
1233
1234        // End disable author name
1235
1236
1237                if (($page['section']) == 'categories' AND !empty($page['category']))
1238                {
1239                        // Step 1
1240           
1241                        $query = '
1242                                SELECT *
1243                                FROM ' . CONCOURS_TABLE .'
1244                                WHERE category =' . $page['category']['id'] . '
1245                                AND time_to_sec(TIMEDIFF(begin_date,now())) < 0
1246                                AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
1247                                ';
1248
1249                        $result = pwg_query($query);
1250
1251                        while ($row = pwg_db_fetch_array($result))
1252                        {
1253                                if (!is_a_guest() AND !empty($row['groups']))
1254                                {
1255
1256                                        if (is_admin() AND $row['admin'])       // allow admin
1257                                                $concours = $row;
1258                                        else
1259                                        {               
1260                                                $authorized_groups = explode(',', $row['groups']);
1261                                                if (array_intersect($this->user_groups, $authorized_groups) == array())
1262                                                        continue;
1263                                                // If no group is parameter for that concours  ==> available for all registered users
1264                                                $concours = $row;
1265                                        }
1266                                }
1267                else 
1268                                       
1269                                        $concours = $row;
1270                        }
1271                        //------------
1272                        // Step 1 bis
1273                        // Actual user is  the author of the picture ==>end
1274                        // for the image, check (depending the config) if user = author or addedby or none
1275                        if ($this->check_img_user($page['current_item']))
1276                        {
1277                                return;
1278                        }
1279                               
1280                        // Check if user is guest and if guest is allowed
1281                        if (is_a_guest() AND array_key_exists('guest', $concours) AND !$concours['guest'])
1282                                return;
1283                        // Check if user is admin and if admin is allowed
1284                        if (is_admin() AND (!isset($concours['admin']) OR (isset($concours['admin']) AND !$concours['admin'])))
1285                                return;
1286                       
1287                        //------------
1288                        // Step 2
1289                        if ($concours != array())
1290                        {
1291                                // If user validate the notation
1292                                if (isset($_POST['concours_submit']))
1293                                {
1294         
1295//                    array_push($page['infos'] , l10n('concours_vote_saved'));
1296                   
1297                                        $user_note = "";
1298                                       
1299                                        // concat all the notes to save on db
1300                                        $firstcriterias = $this->get_firstlevel_criterias($concours['id']);
1301                                        foreach ($firstcriterias as $criteria)
1302                                        {
1303                                                // First without sub criterias
1304                                                if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours['id'] ))
1305                                                {
1306                                                        // Check value
1307                                                        $value = str_replace(",",".",(isset($_POST[$criteria['criteria_id']]) ? $_POST[$criteria['criteria_id']] : floatval($criteria['min_value'])));
1308                                                        $value = str_replace(" ","",$value);
1309                                                        $value = floatval($value);
1310                                                        if ($value < floatval($criteria['min_value']))
1311                                                                $value = floatval($criteria['min_value']);
1312                                                        if ($value > floatval($criteria['max_value']))
1313                                                                $value = floatval($criteria['max_value']);
1314
1315                                                        $user_note .= (strlen($user_note) != 0 ? ";" : "").$criteria['criteria_id']."=".$value;
1316                                                }
1317                                                else
1318                                                {
1319                                                        $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours['id'] );
1320                                                        foreach ($secondcriterias as $subcriteria)
1321                                                        {
1322                                                                // Check value
1323                                                                $value = str_replace(",",".",(isset($_POST[$subcriteria['criteria_id']]) ? $_POST[$subcriteria['criteria_id']] : floatval($subcriteria['min_value'] )));
1324                                                                $value = str_replace(" ","",$value);
1325                                                                $value = floatval($value);
1326                                                                if ($value < floatval($subcriteria['min_value']))
1327                                                                        $value = floatval($subcriteria['min_value']);
1328                                                                if ($value > floatval($subcriteria['max_value']))
1329                                                                        $value = floatval($subcriteria['max_value']);
1330                                                       
1331                                                                $user_note .= (strlen($user_note) != 0 ? ";" : "").$subcriteria['criteria_id']."=".$value;
1332                                                        }
1333                                                }
1334                                        }
1335                               
1336                                        $this->store_img_note_user($page['current_item'], $user_note, $concours['id'], $user['ipguest']);
1337                                        $this->store_img_comment_user($page['current_item'], $_POST['concours_comment'], $concours['id'], $user['ipguest']);
1338                                }
1339
1340                                // If user want to erase notes
1341                                if (isset($_POST['concours_raz']))
1342                                {
1343                                        $this->delete_img_note_user($page['current_item'], $concours['id'], $user['ipguest']);
1344                                        $user_notes = array();
1345                                }
1346                                else
1347                                {
1348                                        // Recover previous note in DB (if exists)
1349                                        $user_notes = $this->get_img_note_user($page['current_item'], $concours['id'], $user['id'], $user['ipguest']);
1350                                }
1351                               
1352                                // Comment is not RAZ, always restore                           
1353                                $comment = $this->get_img_comment_user($page['current_item'], $concours['id'], $user['id'], $user['ipguest']);
1354
1355                                //------------
1356                                // Step 3
1357                                // Recover all 1st level criterias
1358                                $firstcriterias = $this->get_firstlevel_criterias($concours['id']);
1359                                foreach ($firstcriterias as $criteria)
1360                                {
1361                                        // First without sub criterias
1362                                        if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours['id'] ))
1363                                        {
1364                                                $template->append( 'concours_criteria', array(
1365                                                                'nosub' => true,
1366                                                                'level' => 1,
1367                                                                'id'    => $criteria['criteria_id'],                            // id du critere
1368                                                                'name'  => $criteria['name'],                           // id du critere
1369                                                                'lib'   => $criteria['descr'], //.'(min='$criteria['min_value'].';max='.$criteria['min_value'].')',                     // libelle du critrer
1370                                                                'val'   => (isset($user_notes[$criteria['criteria_id']])?$user_notes[$criteria['criteria_id']] : $criteria['min_value']),               //  valeur du critere
1371                                                                'min'   => $criteria['min_value'],                              // min
1372                                                                'max'   => $criteria['max_value']                               // max
1373                                                        ));
1374                                        }
1375                                        else
1376                                        {
1377                                                $template->append( 'concours_criteria', array(
1378                                                                'nosub' => false,
1379                                                                'level' => 1,
1380                                                                'id'    => $criteria['criteria_id'],                            // id du critere
1381                                                                'name'  => $criteria['name'],                           // id du critere
1382                                                                'lib'   => $criteria['descr']
1383                                                        ));
1384                                                $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours['id'] );
1385                                                foreach ($secondcriterias as $subcriteria)
1386                                                {
1387                                                        $template->append( 'concours_criteria', array(
1388                                                                        'nosub' => true,
1389                                                                        'level' => 2,
1390                                                                        'id'    => $subcriteria['criteria_id'],                         // id du critere
1391                                                                        'name'  => $subcriteria['name'],                                // id du critere
1392                                                                        'lib'   => $subcriteria['descr'], //.'(min='$criteria['min_value'].';max='.$criteria['min_value'].')',                  // libelle du critrer
1393                                                                        'val'   => (isset($user_notes[$subcriteria['criteria_id']])?$user_notes[$subcriteria['criteria_id']] : $subcriteria['min_value']),
1394                                                                        'min'   => $subcriteria['min_value'],                           // min
1395                                                                        'max'   => $subcriteria['max_value']                            // max
1396                                                                ));
1397                                                       
1398                                                }
1399                                        }
1400
1401                                }
1402                                // Add the comment
1403                                $template->assign( 'CONCOURS_COMMENT', $comment);
1404
1405                                // if a user has already vote for this photo, check if the score change is allowed
1406
1407
1408                if ($user_notes == array() OR $this->my_config['concours_change_score'])  // Allow user to change his vote after a validation
1409                    $template->assign( 'CONCOURS_CHANGE_SCORE', true);
1410                else
1411                    $template->assign( 'CONCOURS_CHANGE_SCORE', false);
1412               
1413                                $noteuser = $this->get_img_globalnote_user($page['current_item'], $concours['id'], null, $user['ipguest']);
1414                                // Add concours informations on template
1415                                $template->assign( 'concours_infos', array(
1416                                                        'name'  => $concours['name'],
1417                                                        'descr' => $concours['descr'],
1418                            'note'  => ($noteuser >= 0 ? $noteuser : 0 ),
1419                                                        'begin_date' => $concours['begin_date'],
1420                                                        'end_date' => $concours['end_date'],
1421                                                        'end_concours_min' => (strtotime($concours['end_date'])-time()) ,
1422                                                        'max_note' => $this->get_concours_maxnote($concours['id']),
1423                                                        'deadline_type' => $this->my_config['concours_deadline']
1424                                                                ));
1425                               
1426
1427                                $template->assign( 'SCORE_MODE', $this->my_config['score_mode']);
1428                                $template->assign( 'TEXT_OVERLAY', $this->my_config['text_overlay']);
1429                       
1430                                $template->set_filenames(array('concours' =>  CONCOURS_ROOT.'/template/concours.tpl'));
1431                                $template->concat('COMMENT_IMG', $template->parse('concours', true));
1432
1433                                $template->assign('INFO_AUTHOR',l10n('concours_img_author'));
1434                        }
1435                }
1436        }
1437
1438       
1439        // RAZ notation from user to db
1440        // fill criterias notes to 0 in DB
1441        // return false if error
1442        function delete_img_note_user($img_id, $concours_id = NULL, $ipguest = null, $userid=null)
1443        {
1444                global $user;
1445               
1446                if ($concours_id === null)
1447                        if ($this->concours_id !== null)
1448                                $concours_id = $this->concours_id;
1449                        else
1450                                return false;
1451                               
1452                $query = '
1453                DELETE FROM ' . CONCOURS_DATA_TABLE .'
1454                WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ).'
1455                AND user_id = '.($userid == null ? $user['id'] : $userid).'
1456                AND img_id = '.$img_id.
1457                ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')           
1458                .';';
1459
1460                return pwg_query($query);
1461
1462        }
1463       
1464       
1465        // RAZ notation from user to db
1466        // fill criterias notes to 0 in DB
1467        // return false if error
1468        function RAZ_img_note_user($img_id, $concours_id = NULL, $ipguest = null)
1469        {
1470                $user_note = "";
1471                if ($concours_id === null)
1472                        if ($this->concours_id !== null)
1473                                $concours_id = $this->concours_id;
1474                        else
1475                                return false;
1476                               
1477                $firstcriterias = $this->get_firstlevel_criterias($concours_id);
1478                foreach ($firstcriterias as $criteria)
1479                {
1480                        // First without sub criterias
1481                        if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
1482                                $user_note .= (strlen($user_note) != 0 ? ";" : "").$criteria['criteria_id']."=".$criteria['min_value'];
1483                        else
1484                        {
1485                                $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
1486                                foreach ($secondcriterias as $subcriteria)
1487                                        $user_note .= (strlen($user_note) != 0 ? ";" : "").$subcriteria['criteria_id']."=".$subcriteria['min_value'];
1488                        }
1489                }
1490                if (strlen($user_note) != 0)
1491                {
1492                        $this->store_img_note_user($img_id, $user_note, $concours_id, $ipguest);
1493                        return true;
1494                }
1495                else
1496                        return false;
1497        }
1498
1499        // Store notation from user to db
1500        // save with format "criteria_id=note;criteria_id=note..." for data     
1501        function store_img_note_user($img_id, $datas, $concours_id = NULL, $ipguest = null)
1502        {
1503                global $user;
1504                if ($this->get_img_note_user( $img_id, $concours_id, $user['id'], $ipguest) == array() )
1505                {
1506                        $query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id  FROM ' . CONCOURS_DATA_TABLE . ' ;';
1507                        list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
1508
1509                        $query = '
1510                        INSERT INTO ' . CONCOURS_DATA_TABLE .'
1511                                (`id`,
1512                                `id_concours` ,
1513                                `user_id` ,
1514                                `create_date` ,
1515                                `img_id` ,
1516                                `datas`'.
1517                ($ipguest ? ',`ipguest` ' : '')
1518
1519                .')
1520                        VALUES ( '.$next_element_id.','
1521                        .($concours_id !== null ? $concours_id : $this->concours_id ) .'
1522                        , '. $user['id'] .', now(), '.$img_id.', "'.$datas.'"'
1523            .($ipguest ? ',"'.$user['ipguest'].'"' : '')
1524            .');';
1525                }
1526                else
1527                {
1528                        $query = '
1529                        UPDATE ' . CONCOURS_DATA_TABLE .'
1530                        SET datas = "'.$datas.'", create_date = now()
1531                        WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ).'
1532                        AND user_id = '.$user['id'].'
1533                        AND img_id = '.$img_id.
1534            ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')           
1535            .';';
1536                }
1537                pwg_query($query);
1538       
1539        }
1540       
1541        // get notation's user from db
1542        // Return an array with :
1543        // Criteria_id ==> value
1544        // Note : criterias with subcriterias are not saved and not restored. They are calculated for global result
1545        function get_img_note_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null)
1546        {
1547                global $user, $conf;
1548                $img_note = array();
1549                if ($concours_id!== null or $this->concours_id !== null)
1550                {
1551                        $query = '
1552                        SELECT datas
1553                        FROM ' . CONCOURS_DATA_TABLE .'
1554                        WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) 
1555                        . ($ipguest == null ? ' AND user_id = '. ($user_id !== null ? $user_id : $user['id'])
1556                           : ' AND user_id = '.$conf['guest_id'] .' AND ipguest = "'.$ipguest.'"')
1557                        .' AND img_id = '. $img_id 
1558                        .';';
1559            ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
1560                        .';';
1561                        $result = pwg_query($query);
1562                       
1563                        while ($row = pwg_db_fetch_array($result))
1564
1565                        {
1566                                $datas = explode(";",$row['datas']);
1567                                foreach ($datas as $val)
1568                                {
1569                                        if (strpos($val, '=') !== FALSE)
1570                                                $img_note[substr($val, 0, strpos($val, '='))]=substr($val, strpos($val, '=')+1);
1571                                }
1572                        }
1573                       
1574                        return $img_note;
1575                }
1576                else
1577                        return array();
1578        }
1579
1580
1581
1582        // Return the max note for a concours
1583        function get_concours_maxnote($concours_id = NULL)
1584        {
1585
1586                if ($concours_id!== null or $this->concours_id !== null)
1587                {
1588                        $query = '
1589                        SELECT SUM(max_value) AS TOTAL
1590                        FROM ' . CONCOURS_DETAIL_TABLE .'
1591                        WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id)
1592                        .' AND uppercriteria IS NULL' 
1593                        .';';
1594                       
1595                        $result = pwg_query($query);
1596                        if ($this->debug)                                       echo "query=".$query."<br>\n";
1597                       
1598                        if ($row = pwg_db_fetch_array($result))
1599                        {
1600                                return $row['TOTAL'];
1601                        }
1602                        else 
1603                        return -1;
1604                       
1605                }
1606
1607       
1608        }
1609
1610
1611       
1612        // get notation's user from db
1613        // Return the global note for a picture id from a user
1614        // if moderationMode = 1, the 'moderation' contains the GlobalAverage for all the concours
1615        // if moderationMode = 2, the 'moderation' contains the user moderation for all image that are voted by
1616        // return -1 if there is no vote for that user
1617        function get_img_globalnote_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null, $moderationMode = 0, $moderation = 0)
1618        {
1619                global $user, $conf;
1620                $img_note = array();
1621                $global_user_note = -1;
1622                $note_found = false;
1623                if ($concours_id!== null or $this->concours_id !== null)
1624                {
1625                        $query = '
1626                        SELECT datas
1627                        FROM ' . CONCOURS_DATA_TABLE .'
1628                        WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) 
1629                        . ($ipguest == null ? ' AND user_id = '. ($user_id !== null ? $user_id : $user['id'])
1630                           : ' AND user_id = '.$conf['guest_id'] .' AND ipguest = "'.$ipguest.'"')
1631                        .' AND img_id = '. $img_id 
1632                        .';';
1633                        $result = pwg_query($query);
1634                        if ($this->debug)                                       echo "query=".$query."<br>\n";
1635                       
1636                        while ($row = pwg_db_fetch_array($result))
1637                        {
1638                                $global_user_note = 0; // init note if one vote is present
1639                                $note_found = true;
1640                                $datas = explode(";",$row['datas']);
1641                                foreach ($datas as $val)
1642                                {
1643                                        if (strpos($val, '=') !== FALSE)
1644                                                $img_note[substr($val, 0, strpos($val, '='))]=substr($val, strpos($val, '=')+1);
1645                                }
1646                        }
1647                       
1648                        $firstcriterias = $this->get_firstlevel_criterias($concours_id);
1649                        foreach ($firstcriterias as $criteria)
1650                        {
1651                                // First without sub criterias
1652                                if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
1653                                {
1654                                        if (isset($img_note[$criteria['criteria_id']]))
1655                                                $global_user_note += (int)$criteria['ponderation'] * (float)$img_note[$criteria['criteria_id']];
1656                                }
1657                                else
1658                                {
1659                                        $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
1660                                        foreach ($secondcriterias as $subcriteria)
1661                                        {
1662                                                if (isset($img_note[$subcriteria['criteria_id']]))
1663                                                $global_user_note += (int)$subcriteria['ponderation'] * (float)$img_note[$subcriteria['criteria_id']];
1664                                        }
1665                                }
1666                        }
1667                       
1668                        // MODERATION
1669                                // moderation 1 => For each photo without note (user = author or user != author but no vote) add each user avaerage to the total of note and calcul the average
1670                                // moderation 2 => For each photo with note, adapt/change all the value with the moderation value : user note + moderation.
1671                       
1672                        if ($user_id !== null) // only for user
1673                        {
1674                                if ($moderationMode == 1 && !$note_found)
1675                                {               // Moderation1
1676                                        $global_user_note = $moderation;
1677                                }
1678                                elseif ($moderationMode == 2 && $note_found)
1679                                {       // Moderation2
1680                                        $global_user_note += $moderation;
1681                                }               
1682                               
1683                               
1684                        }
1685                        return $global_user_note;
1686                }
1687                else
1688                        return array();
1689               
1690               
1691        }
1692
1693        // Store comment from user to db
1694        function store_img_comment_user($img_id, $datas, $concours_id = NULL, $ipguest = null)
1695        {
1696                global $user;
1697                if (($comment = $this->get_img_note_user( $img_id, $concours_id, null, $ipguest)) == false)
1698                {
1699                        $query = 'SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id  FROM ' . CONCOURS_DATA_TABLE . ' ;';
1700                        list($next_element_id) = pwg_db_fetch_array(pwg_query($query));
1701
1702                        $query = '
1703                        INSERT INTO ' . CONCOURS_DATA_TABLE .'
1704                                (`id`,
1705                                `id_concours` ,
1706                                `user_id` ,
1707                                `create_date` ,
1708                                `img_id` ,
1709                                `comment`'
1710                .($ipguest ? ' `ipguest`' : '').
1711                ')
1712                        VALUES ( '.$next_element_id.','
1713                        .($concours_id !== null ? $concours_id : $this->concours_id ) .'
1714                        , '. $user['id'] .', now(), '.$img_id.', "'.$datas.'");';
1715                }
1716                else
1717                {
1718                        $query = '
1719                        UPDATE ' . CONCOURS_DATA_TABLE .'
1720                        SET comment = "'.$datas.'", create_date = now()
1721                        WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id ).'
1722                        AND user_id = '.$user['id'].'
1723                        AND img_id = '.$img_id.
1724            ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
1725            .';';
1726                }
1727                        pwg_query($query);
1728        }
1729       
1730       
1731        // Get comment on an image for a user
1732        function get_img_comment_user($img_id, $concours_id = NULL, $user_id = null, $ipguest = null)
1733        {
1734                global $user;
1735                $datas = false;
1736                if ($concours_id!== null or $this->concours_id !== null)
1737                {
1738                        $query = '
1739                        SELECT comment
1740                        FROM ' . CONCOURS_DATA_TABLE .'
1741                        WHERE id_concours =' . ($concours_id !== NULL ? $concours_id : $this->concours_id) . '
1742                        AND user_id = '. ($user_id !== null ? $user_id : $user['id']).'
1743                        AND img_id = '. $img_id .
1744            ($ipguest ? ' AND ipguest = "'.$ipguest.'"' : '')
1745                        .';';
1746
1747                        $result = pwg_query($query);
1748                       
1749                        while ($row = pwg_db_fetch_array($result))
1750                                $datas = $row['comment'];
1751                }
1752                return $datas;
1753        }
1754       
1755       
1756        // Generate csv file for a closed concours with result generated
1757        function generate_csv($concours_id = NULL)
1758        {
1759        global $conf;
1760                $file = "rang, id_concours,method, img_id, img_name, img_file, date, note, moyenne, nbvotant, datas\r\n";
1761
1762                if (!(isset($this->concours_infos['method'])))
1763                        $this->concours_infos['method'] = 1;
1764                       
1765                // recover all img_id from the category
1766                $query = 'SELECT id_concours,method, img_id, IMG.name, IMG.file, date, note, moyenne, nbvotant, datas'
1767                .' FROM ' .CONCOURS_RESULT_TABLE
1768                .' INNER JOIN ' . CONCOURS_TABLE.' AS CONC on CONC.id = id_concours'
1769                .' INNER JOIN ' . IMAGES_TABLE.' AS IMG on IMG.id = img_id'
1770                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id );
1771               
1772                if ($this->concours_infos['method'] == 1)       // total
1773                        $query .= ' ORDER BY note DESC';
1774                elseif ($this->concours_infos['method'] == 2)   // moyenne
1775                        $query .= ' ORDER BY moyenne DESC';
1776               
1777                $query .=';';
1778               
1779                $result = pwg_query($query);
1780                // For each images
1781                $rang = 1;
1782                while ($row = pwg_db_fetch_array($result))
1783                {
1784                        $file .= ($row['nbvotant'] != 0 ? $rang : 'N/A').', '
1785                                        .$row['id_concours'].', '
1786                                        .$row['method'].', '
1787                                        .$row['img_id'].', '
1788                                        .$row['name'].', '
1789                                        .$row['file'].', '
1790                                        .$row['date'].', '
1791                                        .$row['note'].', '
1792                                        .$row['moyenne'].', '
1793                                        .$row['nbvotant'].', '
1794                                        .($row['datas'] != null ? $row['datas'] : '')
1795                                        ."\r\n";
1796                        $rang ++;
1797                }
1798                               
1799                return $file;
1800       
1801               
1802        }
1803
1804        // Generate csv file for a closed concours with result generated and all users informations
1805        function generate_detail_csv($concours_id = NULL)
1806        {
1807        global $conf;
1808                $MethodType = "0";
1809                if ($concours_id === null)
1810                        $concours_id = $this->concours_id;
1811                // Prepare the list of criteria
1812                $criteria_list = "";
1813                $firstcriterias = $this->get_firstlevel_criterias($concours_id);
1814                $ident1 = 1;
1815                foreach ($firstcriterias as $criteria)
1816                {
1817                        // format (id:name)
1818                        $criteria_list .= (strlen($criteria_list) ? "," : "")
1819                                                                .$ident1.":".$criteria['name']
1820                                                                ."(id=".$criteria['criteria_id'].")";
1821                        // First wit sub criterias
1822                        if ($this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
1823                        {
1824                                $ident2 = 1;
1825                                $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
1826                                foreach ($secondcriterias as $subcriteria)
1827                                {
1828                                        // format (id:name)
1829                                        $criteria_list .= (strlen($criteria_list) ? "," : "")
1830                                                                          .$ident1.".".$ident2
1831                                                                          .":".$subcriteria['name']."(id=".$subcriteria['criteria_id'].")";
1832                                        $ident2 ++;
1833                                }
1834                        }
1835                        $ident1++;
1836                }
1837                $user_list = array();
1838                $users_criteria = "";
1839       
1840       
1841                // Get all the users who have notes for the concours
1842                $query = 'SELECT distinct(user_id), USER.username'
1843                .' FROM ' .CONCOURS_DATA_TABLE
1844                .' INNER JOIN ' . USERS_TABLE.' AS USER on USER.id = user_id'
1845                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
1846        // Dont take the guest informations because
1847        .' AND user_id <> '.$conf['guest_id']
1848        .' ORDER BY username ASC'
1849                .';';
1850                $result = pwg_query($query);
1851                // For each user
1852                while ($row = pwg_db_fetch_array($result))
1853                {
1854                        array_push($user_list, $row);
1855                        $users_criteria .= (strlen($users_criteria) ? "," : "")."user, user_global_note, comment, ".$criteria_list;
1856                }
1857       
1858        $ipguest = array();
1859        // Get guest info (if available)
1860        if ($this->concours_infos['guest'])
1861        {
1862            $ipguest = $this->get_guest_list();
1863            // For each guest
1864            foreach ( $ipguest as $i => $userid ) //on parcours le tableau
1865            {
1866                $users_criteria .= (strlen($users_criteria) ? "," : "")."user, user_global_note, comment, ".$criteria_list;               
1867            }       
1868        }
1869
1870               
1871                // All informations in csv format
1872                $file = "rang, id_concours, method, nom_concours, date_debut, date_fin, date_export, img_id, img_name, img_file, img_author, note, moyenne, moderation1, moderation2, nbvotant, datas,"
1873                .$users_criteria 
1874                ."\r\n";
1875
1876                // nb of users who vote for each image
1877
1878        // NOT NEEDED, INFO STORE IN DATABASE 'RESULT'
1879                $nbvotes = $this->nb_votes_by_img($concours_id);
1880
1881                // recover all img_id from the category
1882                if (!(isset($this->concours_infos['method'])))
1883                        $this->concours_infos['method'] = 1;
1884                $query = 'SELECT id_concours, method, img_id, IMG.name, IMG.file, IMG.author, date, note, moyenne, moderation1, moderation2, nbvotant, datas, comment'
1885                .' FROM ' .CONCOURS_RESULT_TABLE
1886                .' INNER JOIN ' . CONCOURS_TABLE.' AS CONC on CONC.id = id_concours'
1887                .' INNER JOIN ' . IMAGES_TABLE.' AS IMG on IMG.id = img_id'
1888                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id );
1889               
1890                switch ($this->concours_infos['method'])
1891                {
1892                case 1 :        // total
1893                        $query .= ' ORDER BY note DESC';
1894                        $MethodType = "1-Sum";
1895                        break;
1896                case  2 :       // moyenne
1897                        $query .= ' ORDER BY moyenne DESC';
1898                        $MethodType = "2-Average";
1899                        break;
1900                case  3 :       // moderation1
1901                        $query .= ' ORDER BY moderation1 DESC';
1902                        $MethodType = "3-Average(Mod1)";
1903                        break;
1904                case  4 :       // moderation2
1905                        $query .= ' ORDER BY moderation2 DESC';
1906                        $MethodType = "4-Average(Mod2)";
1907                        break;
1908                }
1909                               
1910                $query .=';';
1911               
1912                $result = pwg_query($query);
1913                // For each images
1914                $rang = 1;
1915        $previousNote = $previousMoy = 0;
1916
1917                while ($row = pwg_db_fetch_array($result))
1918                {
1919            // Check and verify for exaequo
1920            if ($this->my_config['check_exaequo'])
1921            {
1922                if ( ($this->concours_infos['method'] == 1      // total
1923                       AND ($row['note'] == $previousNote))
1924                     OR  ($this->concours_infos['method'] == 2  // moyenne
1925                          AND ($row['moyenne'] == $previousMoy)))
1926                {
1927                    $rang --;         
1928                }
1929            }
1930           
1931                        $file .= ($row['nbvotant'] != 0 ? $rang : 'N/A').', '
1932                                        .$row['id_concours'].', '
1933                                        .$MethodType.', '
1934                                        .str_replace(",", "",$this->concours_infos['name']).', '
1935                                        .$this->concours_infos['begin_date'].', '
1936                                        .$this->concours_infos['end_date'].', '
1937                                        .$row['date'].', '
1938
1939                                        .$row['img_id'].', '
1940                                        .str_replace(",", "",$row['name']).', '
1941                                        .$row['file'].', '
1942                                        .$row['author'].', '
1943                                        .$row['note'].', '
1944                                        .$row['moyenne'].', '
1945                                        .$row['moderation1'].', '
1946                                        .$row['moderation2'].', '
1947                                        .$row['nbvotant'].', '
1948                                        .($row['datas'] != null ? $row['datas'] : '')
1949                                        ;
1950                        foreach ($user_list as $uuser)
1951                        {
1952
1953                                $comment = $this->get_img_comment_user($row['img_id'], $concours_id, $uuser['user_id']);
1954                       
1955                                $user_note = $this->get_img_note_user($row['img_id'], $concours_id, $uuser['user_id']);
1956                               
1957                                $user_global_note = $this->get_img_globalnote_user($row['img_id'], $concours_id, $uuser['user_id']);
1958                                $file .= ', '.$uuser['username'].', '.($user_global_note >= 0 ? $user_global_note  : 0)
1959                                                .', '.($comment != false ? str_replace(array(",","\r\n", "\n", "\r"), " ",$comment) : '')
1960                                                .', '
1961                                                ;
1962
1963                                $user_note_by_crit = "";
1964                                foreach ($firstcriterias as $criteria)
1965                                {
1966                                        // First without sub criterias
1967                                        if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
1968                                        {
1969                                                $user_note_by_crit .= (strlen($user_note_by_crit) ? "," : "").(isset($user_note[$criteria['criteria_id']]) ? $user_note[$criteria['criteria_id']] : ' ');
1970                                        }
1971                                        else
1972                                        {
1973                                                $user_note_by_subcrit = "";
1974                                                $subcrit_note = 0;
1975                                                $user_has_vote = false;
1976                                                $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
1977                                                foreach ($secondcriterias as $subcriteria)
1978                                                {
1979                                                        if (isset($user_note[$subcriteria['criteria_id']]))             $user_has_vote = true;
1980                                                        $user_note_by_subcrit .= (strlen($user_note_by_subcrit) ? "," : "").(isset($user_note[$subcriteria['criteria_id']]) ? $user_note[$subcriteria['criteria_id']] : ' ');
1981                                                        $subcrit_note += (int)$subcriteria['ponderation'] * (float)(isset($user_note[$subcriteria['criteria_id']]) ? $user_note[$subcriteria['criteria_id']] : 0);
1982
1983                                                }
1984                                                $user_note_by_crit .= (strlen($user_note_by_crit) ? "," : "").($user_has_vote ? $subcrit_note : ' ').",".$user_note_by_subcrit;
1985                                        }
1986                                }
1987                                $file .= $user_note_by_crit;
1988
1989                        }
1990
1991            // Add guest infos (if present)
1992                        foreach ($ipguest as $ipguestt)
1993                        {
1994                                $comment = $this->get_img_comment_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
1995                       
1996                                $user_note = $this->get_img_note_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
1997                                $user_global_note = $this->get_img_globalnote_user($row['img_id'], $concours_id, $conf['guest_id'], $ipguestt);
1998                               
1999                                $file .= ', Guest('.$ipguestt.'), '.($user_global_note >= 0 ? $user_global_note : 0)
2000                                                .', '.($comment != false ? str_replace(array(",","\r\n", "\n", "\r"), " ",$comment) : '')
2001                                                .', '
2002                                                ;
2003
2004                                $user_note_by_crit = "";
2005                                foreach ($firstcriterias as $criteria)
2006                                {
2007                                        // First without sub criterias
2008                                        if (!$this->is_criterias_contains_sub($criteria['criteria_id'],$concours_id ))
2009                                        {
2010                                                $user_note_by_crit .= (strlen($user_note_by_crit) ? "," : "").(isset($user_note[$criteria['criteria_id']]) ? $user_note[$criteria['criteria_id']] : ' ');
2011                                        }
2012                                        else
2013                                        {
2014                                                $user_note_by_subcrit = "";
2015                                                $subcrit_note = 0;
2016                                                $user_has_vote = false;
2017                                                $secondcriterias = $this->get_subcriterias($criteria['criteria_id'], $concours_id );
2018                                                foreach ($secondcriterias as $subcriteria)
2019                                                {
2020                                                        if (isset($user_note[$subcriteria['criteria_id']]))             $user_has_vote = true;
2021                                                        $user_note_by_subcrit .= (strlen($user_note_by_subcrit) ? "," : "").(isset($user_note[$subcriteria['criteria_id']]) ? $user_note[$subcriteria['criteria_id']] : ' ');
2022                                                        $subcrit_note += (int)$subcriteria['ponderation'] * (float)(isset($user_note[$subcriteria['criteria_id']]) ? $user_note[$subcriteria['criteria_id']] : 0);
2023
2024                                                }
2025                                                $user_note_by_crit .= (strlen($user_note_by_crit) ? "," : "").($user_has_vote ? $subcrit_note : ' ').",".$user_note_by_subcrit;
2026                                        }
2027                                }
2028                                $file .= $user_note_by_crit;
2029
2030                        }
2031           
2032                        $file .="\r\n";
2033                        $rang ++;
2034            $previousNote = $row['note'];
2035            $previousMoy = $row['moyenne'];
2036
2037                }
2038                return utf8_decode($file);
2039       
2040               
2041        }
2042       
2043       
2044        // Save csv datas to physical file
2045        function save_file($file,$concours_id = NULL)
2046        {
2047                // check if already saved file
2048                if ($filename = $this->get_file_name($concours_id))
2049                        return $filename;
2050                else
2051                {
2052                        $dirpath = CONCOURS_RESULT_FOLDER;
2053
2054                        $filename = date('Ymd')."_concours".($concours_id !== null ? $concours_id : $this->concours_id ).".csv";
2055                        if (!is_dir($dirpath)) 
2056                                @mkdir($dirpath);
2057                        if (file_exists($dirpath. $filename))
2058                                unlink($dirpath. $filename);
2059
2060                        $fh = fopen($dirpath. $filename, 'w') or die("can't open file");
2061                        fwrite($fh, $file);
2062                        fclose($fh);
2063
2064                        //update result database with filename
2065                        $query = "UPDATE " . CONCOURS_RESULT_TABLE . "
2066                                                SET
2067                                                file_name = \"".$filename."\"
2068                                                WHERE id_concours= ".($concours_id !== NULL ? $concours_id : $this->concours_id)."
2069                                                ;";
2070                        pwg_query($query);
2071                       
2072                        return $filename;
2073                }
2074        }               
2075
2076        // Get result file name from db
2077        function get_file_name($concours_id = NULL)
2078        {
2079                $query = 'SELECT distinct(file_name)'
2080                .' FROM ' .CONCOURS_RESULT_TABLE
2081                .' WHERE id_concours = '.($concours_id !== null ? $concours_id : $this->concours_id )
2082                .';';
2083                $result = pwg_query($query);
2084                if ($result)
2085                {
2086                        $row = pwg_db_fetch_array($result);             
2087                        if ($row)
2088                                return $row['file_name'];
2089                        else
2090                                return false;
2091                }
2092        }
2093
2094        // Get csv datas from a saved file
2095        function get_file($concours_id = NULL)
2096        {
2097                $filename = CONCOURS_RESULT_FOLDER.
2098                $size = filesize($filename);
2099                header('Content-Type: application/octet-stream');
2100                header('Content-Length: '.$size);
2101                header('Content-Disposition: attachment; filename='.$filename);
2102                header('Content-Transfer-Encoding: binary');
2103
2104                $file = @fopen($filename, ‘rb’);
2105                if ($file) {
2106                        // stream the file and exit the script when complete
2107                        fpassthru($file);
2108                }
2109        }
2110       
2111        // DEPRECATED Piwigo 11 Activation page administration
2112/*
2113        function concours_admin_menu($menu)
2114        {
2115            array_push($menu,
2116               array(
2117                    'NAME' => CONCOURS_NAME,
2118                    'URL' => get_root_url().'admin.php?page=plugin-'.CONCOURS_DIR.'-manage'
2119                )
2120            );
2121            return $menu;
2122        }
2123*/
2124       
2125        // register Concours Menubar
2126        public function register_blocks( $menu_ref_arr )
2127        {
2128                $menu = & $menu_ref_arr[0];
2129                if ($menu->get_id() != 'menubar' OR $this->my_config['active_menubar'] == false)
2130                  return;
2131                $menu->register_block( new RegisteredBlock( 'CONCOURS_menu', 'concours', 'ConcoursPhoto'));
2132        }
2133
2134    // initialise menubar's menu.     called by menubar object when making menu
2135        public function blockmanager_apply( $menu_ref_arr )
2136        {
2137
2138                global $user, $template;
2139                $menu = & $menu_ref_arr[0];
2140
2141                if ($this->user_groups == array())
2142                        $this->get_user_groups();
2143               
2144                if ( ($block = $menu->get_block( 'CONCOURS_menu' ) ) != null )
2145                {
2146                        $menu_list=array();
2147
2148                        if(is_admin())
2149                        {
2150
2151                        array_push($menu_list,
2152                          array(
2153                                'NAME' => l10n('concours_admin_add'),
2154                                'TITLE' => l10n('concours_admin_add'),
2155                                'URL' => PHPWG_ROOT_PATH . 'admin.php?page=plugin-' . CONCOURS_DIR . '-add_concours&amp;action=new',
2156                                'REL' => ""
2157                          )
2158                        );
2159                       
2160                        }
2161
2162                        // recover all img_id from the category
2163                        $query = 'SELECT distinct(id_concours), groups, guest, admin, CONC.name'
2164                        .' FROM ' .CONCOURS_RESULT_TABLE
2165                        .' INNER JOIN '.CONCOURS_TABLE. ' AS CONC ON CONC.id = id_concours'
2166                        .' ORDER BY id DESC'
2167                        .';';
2168                       
2169                        $result = pwg_query($query);
2170                        $nb_concours = 1;
2171                       
2172                        // For each concours
2173                        while ($row = pwg_db_fetch_assoc($result))
2174
2175                        {
2176                               
2177                                if ($nb_concours > $this->my_config['nbconcours_menubar'])
2178                                        break;
2179                                       
2180                $conc_to_show = false;  // Default ==> dont show
2181               
2182                // Guest OR admin
2183                                if ((is_a_guest() AND $row['guest'])
2184                                        OR (is_admin() AND $row['admin']))
2185                    $conc_to_show = true;
2186                // Group present
2187                               
2188                               
2189                elseif (!empty($row['groups']))
2190                                {
2191                                        $authorized_groups = explode(',', $row['groups']);
2192                                        if (array_intersect($this->user_groups, $authorized_groups) != array()) 
2193                        $conc_to_show = true;
2194                }
2195                // Allowed for any user (logged)
2196                elseif (empty($row['groups']))
2197                    $conc_to_show = true;
2198               
2199                if ($conc_to_show)
2200                                        {
2201                                        $nb_concours ++;
2202
2203                                        array_push($menu_list,
2204                                          array(
2205                                                'NAME' => $row['name'],
2206                                                'TITLE' => $row['name'],
2207                                                'URL' => './index.php?/concours/'.$row['id_concours'],
2208                                                'EDIT' => (is_admin()? PHPWG_ROOT_PATH . 'admin.php?page=plugin-' . CONCOURS_DIR . 'add_concours&amp;concours=' . $row['id_concours'].'&amp;action=modify':"")
2209                                          )
2210                                        );
2211                                }
2212                        }
2213
2214                  if (count($menu_list))
2215                  {
2216                          $block->template = CONCOURS_ROOT.'/template/concours_menu.tpl';
2217                          $block->data = $menu_list;
2218                  }
2219                }
2220        }
2221
2222        function section_init_concours()
2223        {
2224                global $tokens, $page;
2225                if ($tokens[0] == 'concours')
2226                  $page['section'] = 'concours';
2227                elseif ($tokens[0] == 'concours_vote')
2228                  $page['section'] = 'concours_vote';
2229        }
2230       
2231        function index_concours()
2232        {
2233                global $page;
2234                if (isset($page['section']) and $page['section'] == 'concours')
2235                {
2236                        include(CONCOURS_PATH . 'publish.php');
2237                }
2238        }
2239
2240        function index_vote_concours()
2241        {
2242                global $page;
2243                if (isset($page['section']) and $page['section'] == 'concours_vote')
2244                {
2245                        include(CONCOURS_PATH . 'concours_vote.php');
2246                }
2247        }
2248       
2249       
2250  // Show the global note under the thumbnail
2251  function thumbnail_note($tpl_var, $pictures) 
2252  {
2253        global $page, $user, $template;
2254        $this->get_user_groups();
2255
2256    $user['ipguest'] = null;
2257    if (is_a_guest())
2258    {
2259        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
2260            $IP = $_SERVER['HTTP_X_FORWARDED_FOR']; 
2261        elseif(isset($_SERVER['HTTP_CLIENT_IP']))   
2262            $IP = $_SERVER['HTTP_CLIENT_IP'];   
2263        else
2264            $IP = $_SERVER['REMOTE_ADDR']; 
2265             
2266        // store ip
2267        $user['ipguest'] = $IP;
2268    }
2269
2270        if (($page['section']) == 'categories' AND !empty($page['category']))
2271        {
2272               
2273                $concours = array();
2274
2275                $query = '
2276                        SELECT *
2277                        FROM ' . CONCOURS_TABLE .'
2278                        WHERE category =' . $page['category']['id'] 
2279// comment to load prepared contests and opened contests                                . ' AND time_to_sec(TIMEDIFF(begin_date,now())) < 0'
2280                        . ' AND time_to_sec(TIMEDIFF(now(), end_date)) < 0';
2281
2282                $result = pwg_query($query);
2283                // DEBUG
2284                if ($this->debug) echo $query."\n";
2285                // END DEBUG
2286                while ($row = pwg_db_fetch_array($result))
2287                {                               
2288                        if ((strtotime($row['begin_date'])-time() > 0) AND $this->my_config['mask_thumbnail'])
2289                        {
2290                        // disable picture if contest is prepared for all users
2291                          $i=0;
2292                          while ($i<count($tpl_var))
2293                          {
2294                                  array_splice($tpl_var, $i, 1);
2295                                  array_splice($pictures, $i, 1);
2296                          }     
2297                        $concours = $row;
2298                               
2299                        }
2300                        elseif (is_admin() AND $row['admin'])
2301                                $concours = $row;
2302                        elseif (!is_a_guest() AND !empty($row['groups']))
2303                        {
2304                                $authorized_groups = explode(',', $row['groups']);
2305                                if (array_intersect($this->user_groups, $authorized_groups) == array()) 
2306                                        continue;
2307                                $concours = $row;
2308                        }
2309                       
2310                        // If no group is parameter for that concours  ==> available for all registered users
2311                        else
2312                                $concours = $row;               
2313                }
2314               
2315
2316                if (count($concours))
2317                {               
2318                        // Add timeline for all users.
2319                        if (strtotime($concours['begin_date'])-time() > 0)
2320                        {
2321                                $template->assign('begin_concours_min', (strtotime($concours['begin_date'])-time()));
2322                                $template->assign('deadline_type',$this->my_config['concours_deadline']);
2323                                $template->assign('begin_concours', $concours['begin_date']);
2324                        }
2325                        else
2326                        {
2327                                // Check if user is guest and if guest is allowed
2328                                if ((is_a_guest() AND $concours['guest']) 
2329                                        OR (is_admin() AND $concours['admin'])
2330                                        OR !is_a_guest())
2331                                {
2332                         
2333                                        // check if contest is concours not already open (date begin > now)
2334
2335                               
2336                                       
2337                                                foreach($tpl_var as $cle=>$valeur) 
2338                                                {
2339                                                        // show only if the author is not the active user
2340
2341                                                        $AuthorArray = strip_punctuation2($tpl_var[$cle]['author']);
2342                                                        $AddedByID = ($tpl_var[$cle]['added_by']);
2343                                                        $UserArray = strip_punctuation2($user['username']);
2344
2345                                                        if ($this->my_config['author_vote_available']  == 0 // Allow to vote for all photos (and also show his score)
2346                                                            OR ($this->my_config['author_vote_available'] == 1 // check between author and user
2347                                                                AND (empty($AuthorArray) OR count(array_intersect($AuthorArray, $UserArray)) != count ($AuthorArray))  // Author is the same as user name
2348                                                                )       
2349                                                            OR ($this->my_config['author_vote_available'] == 2 // check between author and user
2350                                                                AND (!isset($AddedByID) OR ($user['id'] != $AddedByID))  // Addedby is the same as user name
2351                                                                ) 
2352                                                            OR ($this->my_config['author_vote_available'] == 3 // check between author OR addedby and user
2353                                                                AND (!isset($AddedByID) OR ($user['id'] != $AddedByID))  // Addedby is the same as user name
2354                                                                AND (empty($AuthorArray) OR count(array_intersect($AuthorArray, $UserArray)) != count ($AuthorArray))  // Author is the same as user name
2355                                                                ) 
2356                                                           )
2357
2358                                                        {
2359                                                                if ($this->my_config['thumb_note'])      // display thumbnail note only if option is activated
2360                                                                {
2361                                                                        $user_global_note = $this->get_img_globalnote_user($tpl_var[$cle]['id'], $concours['id'], $user['id'], $user['ipguest']);
2362                                                                        $tpl_var[$cle]['NAME'] = $tpl_var[$cle]['NAME'].'('.l10n('thumbnail_global_note').': '.($user_global_note >= 0 ? $user_global_note : 0).')';
2363                                                                }
2364                                                        }
2365                                                }
2366                                               
2367                                                // Add deadline on description page     
2368                                                $template->assign('end_concours', $concours['end_date']);
2369                                                $template->assign('end_concours_min', (strtotime($concours['end_date'])-time()));
2370                                                $template->assign('deadline_type',$this->my_config['concours_deadline']);
2371                                                if (isset($this->my_config['active_global_score_page']) AND $this->my_config['active_global_score_page'])       // only if option is activated
2372                                                        $template->assign('global_vote_link', PHPWG_ROOT_PATH . 'index.php?/concours_vote/'.$concours['id']);
2373                                }
2374                               
2375                        }
2376                        $template->assign('IMG_URL', CONCOURS_IMG_PATH);
2377                       
2378                        $template->set_filenames(array('concours_description' =>  CONCOURS_ROOT.'/template/concours_description.tpl'));
2379                        $template->concat('CONTENT_DESCRIPTION', $template->parse('concours_description', true));
2380
2381                }
2382        }
2383       
2384    return $tpl_var;
2385  }
2386
2387        function concours_stuffs_module($modules)
2388        {
2389                array_push($modules, array(
2390                'path' => CONCOURS_PATH.'stuffs_module/',
2391                'name' => l10n('concours_stuffs_name'),
2392                'description' => l10n('concours_stuffs_description'),
2393                )
2394                );
2395                return $modules;
2396        }       
2397       
2398       
2399       
2400        function add_contest_desc()
2401        {       
2402
2403
2404                include_once CONCOURS_PATH.'/stuffs_module/functions.inc.php';
2405                global $page, $user, $template;
2406
2407
2408                if (($page['section']) == 'categories' AND !empty($page['category']))
2409                {
2410
2411                        if ($concoursID = $this->concoursID_on_cat())
2412                        {
2413
2414                                if ($this->is_result_present($concoursID))
2415                                {
2416
2417                                        $concours = new Concours($concoursID);
2418                                        if ($concours->concours_infos['Podium_onCat'])
2419                                        {
2420                                                $block = array();
2421                                                $block['contests'][$concours->concours_infos['id']] = array(
2422                                                                                'ID'    => $concours->concours_infos['id'],
2423                                                                                'NAME'  => $concours->concours_infos['name'],
2424                                                                                'DESCR' => $concours->concours_infos['descr'],
2425                                                                                'BEGIN_DATE'    => format_date($concours->concours_infos['begin_date']),
2426                                                                                'END_DATE'      => format_date($concours->concours_infos['end_date']),
2427                                                                                'METHOD'        => l10n("concours_method".$concours->concours_infos['method']),
2428                                                                                'METHODNB'      => $concours->concours_infos['method'],
2429                                                                                'URL'           => './index.php?/concours/'.$concours->concours_infos['id'],
2430                                                                                'DAYS'          => NbJours($concours->concours_infos['begin_date'], $concours->concours_infos['end_date']),
2431                                                                                'VISIBLE'       => true,
2432                                                                                'NB_VOTANT' => count($concours->get_user_list($concours->concours_infos['id']))+count($concours->get_guest_list($concours->concours_infos['id']))
2433                                                                                );
2434
2435
2436                                                $podium = array();
2437
2438                                                // get podium image informations               
2439                                                        $query = 'SELECT ' 
2440                                                        .' RESULT.id_concours, CONC.name, CONC.descr, CONC.begin_date, CONC.end_date, CONC.method,
2441                                                                RESULT.img_id as id, IMG.name, IMG.author, IMG.file, IMG.path, IMG.added_by,
2442                                                                ic.category_id, cat.name AS catname,
2443                                                                RESULT.date, RESULT.note, RESULT.moyenne, RESULT.moderation1, RESULT.moderation2, RESULT.nbvotant, RESULT.datas'
2444                                                        .' FROM ' .CONCOURS_RESULT_TABLE.' AS RESULT'
2445                                                        .' INNER JOIN ' . CONCOURS_TABLE.' AS CONC on CONC.id = RESULT.id_concours'
2446                                                        .' INNER JOIN ' . IMAGES_TABLE.' AS IMG on IMG.id = RESULT.img_id'
2447                                                        .' INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON IMG.id = ic.image_id'
2448                                                        .' INNER JOIN '.CATEGORIES_TABLE.' AS cat ON ic.category_id = cat.id'
2449                                                        .' WHERE RESULT.id_concours = '.$concours->concours_id
2450                                                        .' ORDER BY '
2451                                                        .($concours->concours_infos['method'] == 1 ? 'note': ($concours->concours_infos['method'] == 2 ? 'moyenne' : ($concours->concours_infos['method'] == 3 ? 'moderation1' : 'moderation2')))
2452                                                        .' DESC'
2453                                                        .' LIMIT 3 OFFSET 0;';
2454
2455
2456                                                $rank = 1;
2457                                                $NB_RESULTS = 0;
2458                                                $results = pwg_query($query);
2459
2460                                                while ($result = pwg_db_fetch_array($results)) 
2461                                                {
2462
2463                                                        $NB_RESULTS ++;
2464                                                        // link on picture.php page
2465                                                        set_make_full_url();
2466                                                        if ( isset($result['category_id']) & isset($result['catname']) ) 
2467                                                        {
2468                                                                $url = duplicate_picture_url(
2469                                                                array(
2470                                                                'image_id' => $result['id'],
2471                                                                'image_file' => $result['file'],
2472                                                                'category' => array(
2473                                                                                                'id' => $result['category_id'],
2474                                                                                                'name' => $result['catname'],
2475                                                                                                'permalink' => ''
2476                                                                                          )
2477                                                                ),
2478                                                                array('start')
2479                                                                );
2480                                                        }
2481                                                        else
2482                                                        {
2483                                                                $url = duplicate_picture_url(
2484                                                                  array(
2485                                                                        'image_id' => $result['id'],
2486                                                                        'image_file' => $result['file']
2487                                                                  ),
2488                                                                  array('start')
2489                                                                );
2490                                                        }       
2491                                                        unset_make_full_url();
2492
2493
2494
2495                                                        $method = ($result['method'] == 1 ? 'note': ($result['method'] == 2 ? 'moyenne' : ($result['method'] == 3 ? 'moderation1' : 'moderation2')));
2496
2497                                                        $block['contests'][$result['id_concours']]['RESULTS'][$rank] = array(
2498                                                        'RANK' => $rank,
2499//                                                      'AUTHOR' => $result['author'],
2500                                                        'AUTHOR' => (strlen($result['author']) === 0 ? get_username($result['added_by']): $result['author']),
2501                                                        'TN_SRC' => DerivativeImage::thumb_url($result),
2502                                                        'XSMALL_SRC' => DerivativeImage::url(IMG_XSMALL, $result),     
2503                                                        'XXSMALL_SRC' => DerivativeImage::url(IMG_XXSMALL, $result),   
2504                                                        'URL'   => $url
2505
2506                                                );
2507                                                $rank++;
2508                                                }
2509
2510                                                $block['contests'][$concours->concours_infos['id']]['nb_results'] = $NB_RESULTS;
2511
2512                                                $template->assign('block', $block);
2513                                                $template->assign('IMG_URL', CONCOURS_IMG_PATH);
2514
2515
2516                                                $template->set_filenames(array('concours_description' =>  CONCOURS_ROOT.'/template/concours_description-podium.tpl'));
2517                                                $template->concat('PLUGIN_INDEX_CONTENT_BEFORE', $template->parse('concours_description', true));
2518                                        }
2519                                }
2520                        }
2521
2522                }       
2523
2524               
2525        }
2526
2527
2528        // retun concours id for the category (if present)
2529        function concoursID_on_cat($category = NULL)
2530        {
2531                global $page;
2532                $concours_present = false;
2533                if (!isset($category))  // param not present
2534                {
2535                        if (($page['section']) == 'categories' AND !empty($page['category']))
2536                                        $category = $page['category']['id'] ;
2537                }
2538
2539                if (isset($category))
2540                {
2541                        $query = '
2542                                SELECT id
2543                                FROM ' . CONCOURS_TABLE .'
2544                                WHERE category =' . $category ;
2545
2546                        $result = pwg_query($query);
2547                        while ($row = pwg_db_fetch_array($result))
2548                                return $row['id'];
2549                }
2550                return false;
2551        }
2552
2553
2554
2555        // Check if a concours is present (prepared or actived) for the category and user group
2556        function concours_present_cat($category = NULL, $no_date = NULL)
2557        {
2558                global $page;
2559                $concours_present = false;
2560                if (!isset($category))  // param not present
2561                {
2562                        if (($page['section']) == 'categories' AND !empty($page['category']))
2563                                        $category = $page['category']['id'] ;
2564                }
2565
2566                if (isset($category))
2567                {
2568                        $query = '
2569                                SELECT *
2570                                FROM ' . CONCOURS_TABLE .'
2571                                WHERE category =' . $category . '
2572                AND time_to_sec(TIMEDIFF(now(), end_date)) < 0
2573                                ';
2574
2575                        $result = pwg_query($query);
2576                        while ($row = pwg_db_fetch_array($result))
2577                                return true;
2578                }
2579                return false;
2580        }
2581
2582
2583        // Disable Metatdata to picture for a prepared or active concours
2584        function disable_meta_to_picture()
2585        {
2586                if (isset($this->my_config['mask_meta']) && $this->my_config['mask_meta'] == true)
2587                {
2588                        if ($this->concours_present_cat())
2589                                pwg_set_session_var('show_metadata', 0 );
2590                }
2591        }
2592
2593       
2594}
2595
2596function strip_punctuation($string) {
2597    $string = strtolower($string);      // lower case
2598    $string = preg_replace("/\p{P}+/", "", $string); // remove punctuation
2599    $string = preg_replace("/\p{Nd}+/", "", $string); // remove numeric
2600    $string = preg_replace("/[\p{Z}\t\r\n\v\f]+/", "", $string); // remove spaces
2601    $string = str_replace(" +", "", $string);   // remove space
2602//echo "stripPunct=".$string."!\n";
2603    return $string;
2604}
2605
2606// return array
2607function strip_punctuation2($string) {
2608    $string = strtolower($string);      // lower case
2609    $string = preg_replace("/\p{P}+/", " ", $string); // remove punctuation by space
2610    $string = preg_replace("/\p{Nd}+/", "", $string); // remove numeric
2611    $string = preg_replace("/[\p{Z}\t\r\n\v\f]+/", " ", $string); // remove spaces by spaces (only 1)
2612//    $string = str_replace(" +", "", $string); // remove space
2613        $stringArray = $returnValue = preg_split('/\\W/', $string, -1, PREG_SPLIT_NO_EMPTY);
2614
2615    return $stringArray;
2616}
2617
2618
2619
2620?>
Note: See TracBrowser for help on using the repository browser.