source: extensions/event_cats/include/evntcats_funcs.inc.php @ 4163

Last change on this file since 4163 was 4163, checked in by LucMorizur, 14 years ago

[Event Cats] Begin entry creation in DB

File size: 20.5 KB
Line 
1<?php
2
3// +-----------------------------------------------------------------------+
4// | Piwigo - a PHP based picture gallery                                  |
5// +-----------------------------------------------------------------------+
6// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
7// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
8// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
9// +-----------------------------------------------------------------------+
10// | This program is free software; you can redistribute it and/or modify  |
11// | it under the terms of the GNU General Public License as published by  |
12// | the Free Software Foundation                                          |
13// |                                                                       |
14// | This program is distributed in the hope that it will be useful, but   |
15// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
16// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
17// | General Public License for more details.                              |
18// |                                                                       |
19// | You should have received a copy of the GNU General Public License     |
20// | along with this program; if not, write to the Free Software           |
21// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
22// | USA.                                                                  |
23// +-----------------------------------------------------------------------+
24
25// ***************************************************************************
26// ** evntcats_funcs.php : Functions (include) for Piwigo plugin Event Cats **
27// ***************************************************************************
28
29// +-----------------------------------------------------------------------+
30// | Header                                                                |
31// +-----------------------------------------------------------------------+
32
33global $conf;
34
35include_once(EVNTCATS_PATH.'include/ec_conf.inc.php');
36
37// +-----------------------------------------------------------------------+
38// | Utilities functions                                                   |
39// +-----------------------------------------------------------------------+
40
41/*
42 * is_in($haystack, $needle)
43 * returns true or false whether $needle is a string found in string $haystack
44 *
45 * @param
46 *   $haystack : the string in which to search
47 *   $needle   : the string looked for
48 * @return
49 *   true if $needle is found in $haystack ; false if not
50 */
51function is_in($haystack, $needle) {
52  return (strpos($haystack, $needle) !== false);
53}
54
55/*
56 * ec_image_exists($cat, $img)
57 * returns true or false whether the image is associated with the category.
58 *
59 * @param
60 *   $cat : the category
61 *   $img : the image
62 * @return
63 *   treu or false whether the image is associated with the category.
64 */
65function ec_image_exists($cat, $img) {
66  return (mysql_fetch_row(pwg_query('
67   SELECT *
68   FROM `'.IMAGE_CATEGORY_TABLE.'`
69   WHERE `category_id` = '.$cat.'
70    AND `image_id` = '.$img
71  )) !== false);
72}
73
74/*
75 * str_from_var($var)
76 * returns a string easing array var informations displaying in Piwigo :
77 *   _ the string return value starts with"<p align="left">" ;
78 *   _ all "TAB" characters (chr(10)) are replaced by "<br>" ;
79 *   _ all spaces are replaced by "&nbsp;".
80 *
81 * @param
82 *   $var : variable to display
83 * @return
84 *   string easy to display in Piwigo
85 */
86function str_from_var($var) {
87  return '<p align="left">'.str_replace(chr(10),'<br>',str_replace(' ','&nbsp;', print_r /* var_dump */ ($var,true))).'</p>';
88}
89
90/*
91 * ec_inspect()
92 * goes through ec_lists['ec_table'] to check errors on (multiple) entries
93 * using the same code. Cannot be used elsewhere than here in
94 * build_ec_table() .
95 *
96 * @param
97 *   
98 * @return
99 *   (no return value)
100 */
101function ec_inspect($checked_item, $new_action, $check_ec_nok = true) {
102  global $ec_lists;
103  $first = array();
104  $to_correct = array();
105 
106  // $to_correct is needed cause following code would not work everywhere :
107  /*
108  foreach ($table as $value) {
109    if ($value == $value_to_check and $value == $problem) {
110      foreach ($table as &$value2) { // key index of $table can be reset
111        if ($value2 == $value_to_check) {
112          $value2 = $better_value;
113        }
114      }
115    }
116  }
117  // It works with WinAmp Server, but not on Apache server of Free (french
118  // Internet provider).
119  */
120 
121  foreach ($ec_lists['ec_table'] as &$ec_entry) { // & is not really needed
122    $ec_current_code = $ec_entry['code'];
123    if (
124     $ec_entry['action'] == 'ec_ok' or
125     ($check_ec_nok and $ec_entry['action'] == 'ec_nok')
126    ) {
127      if (isset($first[$ec_current_code])) {
128        // $first[$ec_current_code] is set <=> code has already been met.
129        // Checked item MUST be equal to the first item (thus all items) for
130        // this code.
131        if (
132         $first[$ec_current_code] != $ec_entry[$checked_item] or
133         ($new_action == '' and $ec_entry[$checked_item] == 'true')
134        ) {
135          $to_correct[$ec_current_code] = true; // value not used in fact
136        } // but using $ec_current_code as a key makes a smaller table
137      } // if the error comes back several times
138      else {
139        $first[$ec_current_code] = $ec_entry[$checked_item];
140      }
141    }
142  }
143  foreach ($ec_lists['ec_table'] as &$ec_entry) { // & is needed here
144    if (isset($to_correct[$ec_entry['code']])) {
145      if ($new_action == '') {
146        if (!pwg_query('
147          UPDATE `'.EVNTCATS_TABLE.'`
148          SET `forced` = "false"
149          WHERE `id` = '.$ec_entry['id']
150        )) die('Could not fix a "_f_pb"');
151        $ec_entry['forced'] = 'false';
152      }
153      else $ec_entry['action'] = $new_action;
154    }
155  }
156}
157
158/*
159 * ec_end1()
160 * Process repetitive task when error in database modifying functions.
161 *
162 * @param
163 *   $pst : $_POST argument
164 *   $msg : message
165 * @return
166 *   false as this function is used when there is a problem
167 */
168function ec_end1($pst, $msg) {
169  global $page;
170  $page['errors'][] =
171   l10n($msg).
172   '$_POST[\''.$pst.'\'] = '.
173   $_POST[$pst]
174  ;
175  return false;
176}
177
178/*
179 * ec_end2()
180 * Process repetitive task when error in database modifying functions.
181 *
182 * @param
183 *   $msg : message
184 *   $num : number precising the point where the error occurred
185 * @return
186 *   false as this function is used when there is a problem
187 */
188function ec_end2($msg, $num) {
189  global $page;
190  $page['errors'][] =
191   l10n($msg).' ('.$num.') '.
192   'MySQL error '.mysql_errno().', "'.mysql_error().'"'
193  ;
194  return false;
195}
196
197// +-----------------------------------------------------------------------+
198// | Tables building functions                                             |
199// +-----------------------------------------------------------------------+
200
201/*
202 * build_ec_table()
203 * builds a table showing the content of the <pwg>_event_cats database table,
204 * and a table showing the eventual errors.
205 *
206 * @param
207 *   no parameters passed ; the main material on which works the function, is
208 *   the global array variable $ec_lists.
209 * @return
210 *   (no return value)
211 */
212function build_ec_table() {
213  global $ec_lists, $conf, $ec_ap_ok;
214 
215  $ec_lists['ec_table'] = array();
216 
217  if (isset($conf['auto_log'])) {
218    // For tests purpose : table not in MySQL, but in $conf['xxx'] vars in
219    // config_local.inc.php
220   
221    foreach ($conf['auto_log'] as $ec_current_code => $ec_entry) {
222      $ec_current_entry = array_push($ec_lists['ec_table'], array(
223       'code'    => $ec_current_code,
224       'user_id' => get_userid($ec_entry[$ec_current_code]),
225       'action'  => 'ec_ok',
226       'arg1'    => NULL,
227       'arg2'    => NULL,
228       'forced'  => 'false',
229      )) - 1;
230      $ec_lists['ec_table'][$ec_current_entry]['id'] = $ec_current_entry;
231      if (isset($conf['prior_page'])) {
232        if (array_key_exists($ec_current_code, $conf['prior_page'])) {
233          $ec_lists['ec_table'][$ec_current_entry]['arg2'] =
234           $conf['prior_page'][$ec_current_code];
235          $ec_lists['ec_table'][$ec_current_entry]['forced'] = 'true';
236        }
237      }
238      if (isset($conf['outdated_page'])) {
239        if (array_key_exists($ec_current_code, $conf['outdated_page'])) {
240          $ec_lists['ec_table'][$ec_current_entry]['action'] = 'ec_nok';
241          $ec_lists['ec_table'][$ec_current_entry]['arg2'] =
242           $conf['outdated_page'][$ec_current_code];
243          $ec_lists['ec_table'][$ec_current_entry]['forced'] = 'true';
244        }
245      }
246    }
247   
248    // Inspection of $conf['outdated_page']
249    if (isset($conf['outdated_page'])) {
250      foreach ($conf['outdated_page'] as $ec_current_code => $ec_current_AP) {
251        if (!array_key_exists($ec_current_code, $conf['auto_log'])) {
252          $ec_current_entry = array_push($ec_lists['ec_table'], array(
253           'code'    => $ec_current_code,
254           'user_id' => '',
255           'action'  => 'ec_nok',
256           'arg1'    => NULL,
257           'arg2'    => $ec_current_AP,
258           'forced'  => 'true',
259          )) - 1;
260          $ec_lists['ec_table'][$ec_current_entry]['id'] = $ec_current_entry;
261        }
262      }
263    }
264   
265  }
266  else { // in "normal" use ($conf['auto_log'] NOT set), $ec_lists['ec_table']
267         // is built thanks to below code only. A little bit more simple...
268    $q = pwg_query('
269     SELECT * FROM `'.EVNTCATS_TABLE.'`
270     WHERE `code` IS NOT NULL
271     ORDER BY `id`
272    ');
273    while ($r = mysql_fetch_assoc($q)) {
274      $ec_lists['ec_table'][intval($r['id'])] = $r;
275    }
276  }
277 
278  // Construction of behaviour
279 
280  // Multiple action params for a single code check
281  ec_inspect('action', 'ec_nok_action_pb');
282 
283  // Multiple user_ids for a single code check
284  ec_inspect('user_id', 'ec_nok_userid_pb', false);
285 
286  // Multiple "forced" params for a single code check
287  ec_inspect('forced', '');
288 
289  // User id and associated page validities checks
290  foreach ($ec_lists['ec_table'] as &$ec_entry) {
291   
292    // Check if associated user_id exists
293    if (
294     is_in($ec_entry['action'], 'ec_ok') and
295     !array_key_exists($ec_entry['user_id'], $ec_lists['user_ids'])
296    ) {
297      $ec_entry['action'] = 'ec_nok_userid_miss';
298    }
299   
300    // Check if associated displayed page exists
301    $a = 0;
302    if (!empty($ec_entry['arg1']) and
303     is_in($ec_entry['action'], 'ec_ok')) $a++; // Only arg2
304    // is significant if action is ec_nok[_xxx] .
305    if (!empty($ec_entry['arg2'])) $a+= 2;
306    switch ($a) {
307      // case 0 : home, nothing to check
308     
309      case 2: // Additional Page
310        if (
311          $ec_ap_ok and (
312            is_in($ec_entry['action'], 'ec_ok') or
313            $ec_entry['action'] == 'ec_nok'
314          ) and
315          !array_key_exists($ec_entry['arg2'], $ec_lists['add_pages'])
316        ) {
317          $ec_entry['action'].= '_ap_pb';
318        }
319      break;
320     
321      case 1: // Category
322      case 3: // Image
323        if (is_in($ec_entry['action'], 'ec_ok')) {
324          if (array_key_exists($ec_entry['arg1'], $ec_lists['categories'])) {
325            if ($a == 3) { // case 3: // Image
326              if (!ec_image_exists($ec_entry['arg1'], $ec_entry['arg2'])) {
327                $ec_entry['action'].= '_img_pb';
328              }
329            }
330          }
331          else {
332            $ec_entry['action'].= '_cat_pb';
333          }
334        }
335      break;
336    }
337  }
338}
339
340/*
341 * build_ec_lists()
342 * builds the main array variable contaning all informations for the plugin
343 *
344 * @param
345 *   no parameter passed, the main material on which works the function, is
346 *   the global array variable $ec_lists.
347 * @return
348 *   (no return value)
349 */
350function build_ec_lists() {
351 
352  global $ec_ap_ok, $template, $ec_lists;
353 
354  $ec_lists = array();
355
356  // Construction of $ec_lists['add_pages'] array var
357  $ec_lists['add_pages'] = array();
358  if ($ec_ap_ok) {
359    $res = pwg_query('SELECT id,title FROM '.ADD_PAGES_TABLE);
360    while ($r = mysql_fetch_assoc($res)) {
361      $c = (is_in($r['title'], '/user_id=')) ? '/user_id=' : '/group_id=';
362      $a = explode($c ,$r['title']);
363      $ec_lists['add_pages'][$r['id']] = $a[0];
364    }
365  }
366 
367  // Construction of $ec_lists['categories'] array var
368  $c = array();
369  display_select_cat_wrapper('
370     SELECT id,name,uppercats,global_rank
371     FROM '.CATEGORIES_TABLE,
372   $c, 'category_options', true);
373  $ec_lists['categories'] = $template->smarty->_tpl_vars['category_options'];
374 
375  // Construction of $ec_lists['user_ids'] array var
376  $ec_lists['user_ids'] = array();
377  $q = pwg_query('SELECT id,username FROM '.USERS_TABLE. ' WHERE id > 2');
378  while ($r = mysql_fetch_assoc($q)) {
379    $ec_lists['user_ids'][$r['id']] = $r['username'];
380  }
381 
382  // Construction of $ec_lists['ec_table'] array var
383  build_ec_table();
384}
385
386/*
387 * build_ec_duplicable_codes()
388 *
389 *
390 * @param
391 *   no parameter passed, the main material on which works the function, is
392 *   the global array variable $ec_lists.
393 * @return
394 *   (no return value)
395 */
396function build_ec_duplicable_codes() {
397  global $ec_lists;
398  $ec_lists['duplicable_codes'] = array();
399  $t                            = array();
400  foreach ($ec_lists['ec_table'] as $ec_entry) {
401    if (
402      is_in($ec_entry['action'], 'ec_ok') and
403      $ec_entry['forced'] == 'false'
404    ) {
405      $t[$ec_entry['id']] = $ec_entry['code'];
406      $ec_lists['duplicable_codes']['codes'][$ec_entry['code']]['id'] =
407       $ec_entry['id'];
408      $ec_lists['duplicable_codes']['codes'][$ec_entry['code']]['user_id'] =
409       $ec_entry['user_id'];
410    }
411  }
412  foreach ($t as $ec_id => $ec_code) {
413    $ec_lists['duplicable_codes']['ids'][$ec_id] =
414     $ec_lists['duplicable_codes']['codes'][$ec_code]['id'];
415  }
416}
417
418// +-----------------------------------------------------------------------+
419// | Database modifying functions                                          |
420// +-----------------------------------------------------------------------+
421
422/*
423 * ec_create_entry_OK()
424 * returns true or false whether the creation of a new entry described by
425 * $_POST was OK or not.
426 *
427 * @param
428 *   no param
429 * @return
430 *   true if creation was OK ; false if not
431 */
432function ec_create_entry_OK() {
433  global $page, $ec_lists;
434 
435/*
436
437(
438    [ec_act1] => create
439    [ec_entry_sel] => -1
440    [ec_sel_code] => new
441    [ec_in_up_auto_code_length] => 10
442    [ec_in_up_code] => 94q0V1067D
443    [ec_sel_user] => new
444    [ec_in_up_usr_txt] => san_gimi
445    [ec_in_up_psd_txt] => 7Mv8QxZV
446    [ec_in_up_newgroup] => on
447    [ec_in_up_grp_txt] => EC_san_gimi
448    [ec_input_action] => cat
449    [ec_in_up_cat] => 6
450    [ec_in_up_img] =>
451)
452
453*/
454  /* foreach ($ec_lists['ec_table'] as $ec_entry) {
455    if ($_POST['ec_in_up_code'] == $ec_entry['code'])
456      return ec_end1('ec_in_up_code', 'ec_bad_argument2');
457  }
458  if ($t1 = (in_array($_POST['ec_in_up_usr_txt'], $ec_lists['user_ids'])))
459   $ec_user_id = $_POST['ec_in_up_usr_txt'];
460  if ($_POST['ec_sel_user'] == 'new') {
461    if ($t1) return ec_end1('ec_in_up_usr_txt', 'ec_bad_argument3');
462    else { // New user account creation
463      $page['errors'] = register_user(
464       $_POST['ec_in_up_usr_txt'], $_POST['ec_in_up_psd_txt'], '', false
465      );
466      if (
467        count($page['errors']) != 0 or
468        !($ec_user_id = get_userid($_POST['ec_in_up_usr_txt'])) or
469        !pwg_query("
470          UPDATE `".USER_INFOS_TABLE."`
471          SET `status` = 'generic'
472          WHERE `user_id` = ".$ec_user_id.";
473        ")
474      ) {
475        array_unshift($page['errors'], l10n('ec_user_create_pb'));
476        return false;
477      }
478      if (
479        isset($_POST['ec_in_up_newgroup']) and
480        isset($_POST['ec_in_up_grp_txt']) and
481        $_POST['ec_in_up_grp_txt'] != ''
482      ) { // New group creation, and association with user_id at the same time
483        if (
484          !($t = mysql_fetch_row(pwg_query("
485            SELECT `id`
486            FROM `".GROUPS_TABLE."`
487            WHERE `name` = '".$_POST['ec_in_up_grp_txt']."';
488          ")))
489        ) {
490          if (
491            !pwg_query("
492              INSERT INTO `".GROUPS_TABLE."` (`name`, `is_default`)
493              VALUES ('".$_POST['ec_in_up_grp_txt']."', 'false');
494            ")
495          ) return ec_end2('ec_group_create_pb', '1');
496          if (
497            !($t = mysql_fetch_row(pwg_query("
498              SELECT `id`
499              FROM `".GROUPS_TABLE."`
500              WHERE `name` = '".$_POST['ec_in_up_grp_txt']."';
501            ")))
502          ) return ec_end2('ec_group_create_pb', '2');
503        }
504        if (
505          !(pwg_query("
506            INSERT INTO `".USER_GROUP_TABLE."` (`user_id `, `group_id`)
507            VALUES ('".$ec_user_id."', '".$t['id']."');
508          "))
509        ) return ec_end2('ec_group_create_pb', '3');
510      }
511    }
512  }
513  else {
514    if ($t1) {
515      if (ereg('^[a-zA-Z0-9_-]{4,32}$',$_POST['ec_in_up_code'])) {
516        if
517      }
518      else return ec_end1('ec_in_up_code', 'ec_bad_argument7');
519    }
520    else return ec_end1('ec_in_up_usr_txt', 'ec_bad_argument6');
521  }
522  */
523 
524  $page['errors'][] = 'Y\'a p\'têt\' ben eu une erreur...';
525}
526
527/*
528 * ec_duplicate_entry_OK()
529 * returns true or false whether the duplication of an existing entry which #
530 * is given by $_POST['ec_entry_sel'] was OK or not.
531 *
532 * @param
533 *   no param
534 * @return
535 *   true if creation was OK ; false if not
536 */
537function ec_duplicate_entry_OK() {
538  global $page, $ec_lists;
539 
540  build_ec_duplicable_codes();
541  if (array_key_exists($_POST['ec_entry_sel'],
542   $ec_lists['duplicable_codes']['ids'])) {
543    $arg1 = ''; $arg2 = '';
544    switch ($_POST['ec_input_action']) {
545      case 'add_p':
546        if (array_key_exists($_POST['ec_in_up_aps'],$ec_lists['add_pages'])) {
547         $arg2 = $_POST['ec_in_up_aps']; }
548        else return ec_end1('ec_in_up_aps', 'ec_bad_argument4');
549      case 'home':
550      break;
551      case 'img':
552      case 'cat':
553        if (array_key_exists($_POST['ec_in_up_cat'],
554         $ec_lists['categories'])) {
555          if ($_POST['ec_input_action'] == 'img') {
556            if (
557             ec_image_exists($_POST['ec_in_up_cat'], $_POST['ec_in_up_img'])
558            ) $arg2 = $_POST['ec_in_up_img'];
559            else return ec_end1('ec_in_up_img', 'ec_bad_argument4');
560          }
561          $arg1 = $_POST['ec_in_up_cat'];
562        }
563        else return ec_end1('ec_in_up_cat', 'ec_bad_argument4');
564      break;
565      default: return ec_end1('ec_input_action', 'ec_bad_argument1');
566    }
567    if (pwg_query("
568      INSERT INTO `".EVNTCATS_TABLE."`
569       (`code`, `user_id`, `action`, `arg1`, `arg2`)
570      VALUES (
571        '".$ec_lists['ec_table'][$_POST['ec_entry_sel']]['code']."',
572        '".$ec_lists['ec_table'][$_POST['ec_entry_sel']]['user_id']."',
573        'ec_ok',
574        '".$arg1."',
575        '".$arg2."'
576      );
577    ")) {
578      $page['infos'][] =
579       l10n('ec_entry_dup_ok_pre').
580       $_POST['ec_entry_sel'].' ('.
581       $ec_lists['ec_table'][$_POST['ec_entry_sel']]['code'].')'.
582       l10n('ec_entry_dup_ok_end')
583      ;
584      build_ec_table();
585      return true;
586    }
587    else {
588      $page['errors'][] =
589       l10n('ec_entry_dup_nok_pre1').
590       $_POST['ec_entry_sel'].
591       l10n('ec_entry_dup_nok_end1').
592       'MySQL error '.mysql_errno().', "'.mysql_error().'"'
593      ;
594      return false;
595    }
596  }
597  else return ec_end1('ec_entry_sel', 'ec_bad_argument5');
598}
599
600/*
601 * ec_modify_entry_OK()
602 * returns true or false whether the modification of an existing entry which #
603 * is given by $_POST['ec_entry_sel'] was OK or not.
604 *
605 * @param
606 *   no param
607 * @return
608 *   true if modification was OK ; false if not
609 */
610function ec_modify_entry_OK() {
611  global $page;
612  $page['errors'][] = 'Y\'a pas eu une erreur ?...';
613  return false;
614}
615
616/*
617 * ec_toggle_forced_entry()
618 * Toggles the 'forced' property of an entry, provided it complies to the
619 * rules.
620 *
621 * @param
622 *   no param
623 * @return
624 *   no return value
625 */
626function ec_toggle_forced_entry() {
627  global $page;
628  $page['errors'][] = 'ec_toggle_forced_entry';
629}
630
631/*
632 * ec_delete_entry()
633 * tries to delete an existing entry which # is given by
634 * $_POST['ec_entry_sel'].
635 *
636 * @param
637 *   no param
638 * @return
639 *   no return value : modifies $page['errors'] or $page['infos']
640 */
641function ec_delete_entry() {
642  global $page, $ec_lists;
643  if (array_key_exists($_POST['ec_entry_sel'], $ec_lists['ec_table'])) {
644    if (!pwg_query('
645      DELETE FROM `'.EVNTCATS_TABLE.'`
646      WHERE `id` = '.$_POST['ec_entry_sel']
647    )) {
648      $page['errors'][] =
649        l10n('ec_entry_del_nok_pre').
650        $_POST['ec_entry_sel'].
651        l10n('ec_entry_del_nok_end').
652        'MySQL error '.mysql_errno().', "'.mysql_error().'"'
653      ;
654    }
655    else {
656      $page['infos'][] =
657        l10n('ec_entry_del_ok_pre').
658        $_POST['ec_entry_sel'].
659        l10n('ec_entry_del_ok_end');
660      build_ec_table();
661    }
662  }
663  else ec_end1('ec_entry_sel', 'ec_bad_argument1');
664}
665
666?>
Note: See TracBrowser for help on using the repository browser.