source: extensions/event_cats/include/evntcats_main_funcs.inc.php @ 31810

Last change on this file since 31810 was 26672, checked in by LucMorizur, 10 years ago

Compatibility with Piwigo version 2.6

File size: 19.6 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// Look out, do sit before reading that :
26// keeps file coded in UTF-8 without BOM in Notepad++ : é
27// !!!
28
29if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
30
31// ***************************************************************************
32// ** evntcats_admin_funcs.php : Main functions (include)                   **
33// ** for Piwigo plugin Event Cats                                          **
34// ***************************************************************************
35
36// +-----------------------------------------------------------------------+
37// | Header                                                                |
38// +-----------------------------------------------------------------------+
39
40include_once(EVNTCATS_PATH.'include/ec_conf.inc.php');
41
42if (!isset($ec_lists)) {
43  $ec_lists               = array();
44  $ec_lists['add_pages']  = array();
45  $ec_lists['categories'] = array();
46  $ec_lists['user_ids']   = array();
47  $ec_lists['ec_table']   = array();
48}
49
50// +-----------------------------------------------------------------------+
51// | Utilities functions                                                   |
52// +-----------------------------------------------------------------------+
53
54/*
55 * is_in($haystack, $needle)
56 * returns true or false whether $needle is a string found in string $haystack
57 *
58 * @param
59 *   $haystack : the string in which to search
60 *   $needle   : the string looked for
61 * @return
62 *   true if $needle is found in $haystack ; false if not
63 */
64function is_in($haystack, $needle) {
65  return (strpos($haystack, $needle) !== false);
66}
67
68/*
69 * ec_image_exists($cat, $img)
70 * returns true or false whether the image is associated with the category.
71 *
72 * @param
73 *   $cat : the category
74 *   $img : the image
75 * @return
76 *   treu or false whether the image is associated with the category.
77 */
78function ec_image_exists($cat, $img) {
79  $r = pwg_query("
80    SELECT *
81    FROM `".IMAGE_CATEGORY_TABLE."`
82    WHERE `category_id` = ".$cat."
83     AND `image_id` = ".$img
84  );
85  return (bool)pwg_db_num_rows($r);
86}
87
88/*
89 * str_from_var($var)
90 * returns a string easing array var informations displaying in Piwigo :
91 *   _ the string return value starts with"<p align="left">" ;
92 *   _ all "TAB" characters (chr(10)) are replaced by "<br>" ;
93 *   _ all spaces are replaced by "&nbsp;".
94 *
95 * @param
96 *   $var : variable to display
97 * @return
98 *   string easy to display in Piwigo
99 */
100function str_from_var($var) {
101  return
102   '<p align="left">'.
103   str_replace(
104    chr(10),'<br>',
105    str_replace(' ','&nbsp;', print_r /* var_dump */ ($var,true))
106   ).
107   '</p>';
108}
109
110/*
111 * ec_inspect()
112 * goes through ec_lists['ec_table'] to check errors on (multiple) entries
113 * using the same code. Cannot really be used elsewhere than here in
114 * build_ec_table() .
115 *
116 * @param
117 *   
118 * @return
119 *   (no return value)
120 */
121function ec_inspect($checked_item, $new_action, $check_ec_nok = true) {
122  global $ec_lists;
123  $first = array();
124  $to_correct = array();
125 
126  /*
127  // $to_correct is needed cause following code would not work everywhere :
128  foreach ($table as $value) {
129    if ($value == $value_to_check and $value == $problem) {
130      foreach ($table as &$value2) { // key index of $table can be reset
131        if ($value2 == $value_to_check) {
132          $value2 = $better_value;
133        }
134      }
135    }
136  }
137  // It works with WinAmp Server, but not on Apache server of Free (french
138  // Internet provider).
139  */
140 
141  foreach ($ec_lists['ec_table'] as $ec_entry) {
142    $ec_current_code = $ec_entry['code'];
143    if (
144     $ec_entry['action'] == 'ec_ok' or
145     ($check_ec_nok and $ec_entry['action'] == 'ec_nok')
146    ) {
147      if (isset($first[$ec_current_code])) {
148        // $first[$ec_current_code] is set <=> code has already been met.
149        // Checked item MUST be equal to the first item (thus all items) for
150        // this code.
151        if (
152         $first[$ec_current_code] != $ec_entry[$checked_item] or
153         ($new_action == '' and $ec_entry[$checked_item] == 'true')
154        ) $to_correct[$ec_current_code] = true; // value not used in fact
155        // but using $ec_current_code as a key makes a smaller table
156      } // if the error comes back several times
157      else $first[$ec_current_code] = $ec_entry[$checked_item];
158    }
159  }
160  foreach ($ec_lists['ec_table'] as &$ec_entry) { // & is needed here
161    if (isset($to_correct[$ec_entry['code']])) {
162      if ($new_action == '') {
163        if (!pwg_query("
164          UPDATE `".EVNTCATS_TABLE."`
165          SET `forced` = 'false'
166          WHERE `id` = ".$ec_entry['id']
167        )) die('Could not fix a "_f_pb"');
168        $ec_entry['forced'] = 'false';
169      }
170      else $ec_entry['action'] = $new_action;
171    }
172  }
173}
174
175// Compatibility to Piwigo 2.2 , where this function disappeared
176/** returns the argument_ids array with new sequenced keys based on related
177 * names. Sequence is not case sensitive.
178 * Warning: By definition, this function breaks original keys
179 */
180function ec_order_by_name($element_ids,$name)
181{
182  $ordered_element_ids = array();
183  foreach ($element_ids as $k_id => $element_id)
184  {
185    $key = strtolower($name[$element_id]) .'-'. $name[$element_id] .'-'. $k_id;
186    $ordered_element_ids[$key] = $element_id;
187  }
188  ksort($ordered_element_ids);
189  return $ordered_element_ids;
190}
191
192// +-----------------------------------------------------------------------+
193// | Tables building functions                                             |
194// +-----------------------------------------------------------------------+
195
196/*
197 * build_ec_addp()
198 * builds $ec_lists['add_pages'].
199 *
200 * @param
201 *   (no parameter)
202 * @return
203 *   (no return value)
204 */
205function build_ec_addp() {
206  global $ec_lists;
207  $ec_lists['add_pages'] = array();
208  if (defined('ADD_PAGES_TABLE')) {
209    $res = pwg_query("SELECT `id`, `title` FROM `".ADD_PAGES_TABLE."`;");
210    while ($r = pwg_db_fetch_assoc($res)) {
211      $a = (is_in($r['title'], '/user_id=')) ?
212       explode('/user_id=' , $r['title']) : array($r['title']);
213      $b = (is_in($a[0], '/group_id=')) ?
214       explode('/group_id=' , $a[0]) : $a;
215      $ec_lists['add_pages'][$r['id']] = $b[0];
216    }
217  }
218}
219
220/*
221 * build_ec_categories($dsp)
222 * builds $ec_lists['categories'].
223 *
224 * @param
225 *   whether $ec_lists['categories'] must be of type "cat / sub-cat" or
226 *   or "cat <CR LF> - sub-cat".
227 * @return
228 *   (no return value)
229 */
230function build_ec_categories($dsp) {
231  global $template, $ec_lists;
232  $ec_lists['categories'] = array();
233  $c = array();
234  display_select_cat_wrapper("
235     SELECT `id`, `name`, `uppercats`, `global_rank`
236     FROM `".CATEGORIES_TABLE."`
237   ", $c, 'category_options', $dsp);
238  $ec_lists['categories'] = $template->get_template_vars('category_options');
239}
240
241/*
242 * build_ec_userids()
243 * builds $ec_lists['user_ids'].
244 *
245 * @param
246 *   (no parameter)
247 * @return
248 *   (no return value)
249 */
250function build_ec_userids() {
251  global $ec_lists, $conf;
252  $ec_lists['user_ids'] = array();
253  $ec_lists['user_ids'] = simple_hash_from_query("
254    SELECT
255      ".$conf['user_fields']['id']." AS id,
256      ".$conf['user_fields']['username']." AS username
257    FROM `".USERS_TABLE."`
258    WHERE id > 2;",
259    'id', 'username'
260  );
261}
262
263/*
264 * build_ec_table()
265 * builds a table showing the content of the <pwg>_event_cats database table,
266 * and a table showing the eventual errors.
267 *
268 * @param
269 *   no parameters passed ; the main material on which works the function, is
270 *   the global array variable $ec_lists.
271 * @return
272 *   (no return value)
273 */
274function build_ec_table() {
275  global $ec_lists;
276 
277  $ec_lists['ec_table'] = array();
278  $q = pwg_query("
279    SELECT *
280    FROM `".EVNTCATS_TABLE."`
281    WHERE `code` IS NOT NULL
282    ORDER BY `id`
283  ");
284  while ($r = pwg_db_fetch_assoc($q))
285   $ec_lists['ec_table'][intval($r['id'])] = $r;
286 
287  // Construction of behaviour
288 
289  // Multiple action params for a single code check
290  ec_inspect('action', 'ec_nok_action_pb');
291 
292  // Multiple user_ids for a single code check
293  ec_inspect('user_id', 'ec_nok_userid_pb', false);
294 
295  // Multiple "forced" params for a single code check
296  ec_inspect('forced', '');
297 
298  // User id and associated page validities checks
299  foreach ($ec_lists['ec_table'] as &$ec_entry) {
300   
301    // Check if associated user_id exists
302    if (
303     is_in($ec_entry['action'], 'ec_ok') and
304     !array_key_exists($ec_entry['user_id'], $ec_lists['user_ids'])
305    ) $ec_entry['action'] = 'ec_nok_userid_miss';
306   
307    // Check if associated displayed page exists
308    $a = 0;
309    if (
310      !empty($ec_entry['arg1']) and
311      // (Only arg2 is significant if action is ec_nok[_xxx] .)
312      is_in($ec_entry['action'], 'ec_ok')
313    ) $a++;
314    if (!empty($ec_entry['arg2'])) $a+= 2;
315    switch ($a) {
316      // case 0 : home, nothing to check
317     
318      case 2: // Additional Page
319        if (
320          defined('ADD_PAGES_TABLE') and (
321            is_in($ec_entry['action'], 'ec_ok') or
322            $ec_entry['action'] == 'ec_nok'
323          ) and
324          !array_key_exists($ec_entry['arg2'], $ec_lists['add_pages'])
325        ) $ec_entry['action'].= '_ap_pb';
326      break;
327     
328      case 1: // Category
329      case 3: // Image
330        if (is_in($ec_entry['action'], 'ec_ok')) {
331          if (array_key_exists($ec_entry['arg1'], $ec_lists['categories'])) {
332           if ($a == 3) // case 3: // Image
333            if (!ec_image_exists($ec_entry['arg1'], $ec_entry['arg2']))
334             $ec_entry['action'].= '_img_pb';
335          }
336          else $ec_entry['action'].= '_cat_pb';
337        }
338      break;
339    }
340  }
341}
342
343/*
344 * build_dup_groups()
345 * builds the information telling who is allowed to duplicate
346 *
347 * @param
348 *   no parameter passed, the main material on which works the function, is
349 *   the global array variable $ec_lists.
350 * @return
351 *   (no return value)
352 */
353function build_dup_groups() {
354  global $ec_lists;
355 
356  if (count($ec_lists['user_ids']) == 0) build_ec_userids();
357 
358  // Existing groups (needed later)
359  $ec_lists['groups'] = simple_hash_from_query("
360    SELECT `id`, `name`
361      FROM `".GROUPS_TABLE."`
362      ORDER BY `name` ASC;
363    ",
364    'id', 'name'
365  );
366 
367  // groups granted to duplication
368  $ec_lists['groups_granted_ids'] = ec_order_by_name(
369    array_from_query("
370      SELECT `arg2`
371        FROM ".EVNTCATS_TABLE."
372        WHERE `code` IS NULL
373          AND `arg1` = 1
374          AND `arg2` IS NOT NULL
375      ;",
376      'arg2'
377    ),
378    $ec_lists['groups']
379  );
380 
381  // users directly granted to duplication
382  $ec_lists['users_granted_direct_ids'] = ec_order_by_name(
383    array_from_query("
384      SELECT `arg2`
385        FROM `".EVNTCATS_TABLE."`
386        WHERE `code` IS NULL
387          AND `arg1` = 2
388          AND `arg2` IS NOT NULL
389      ;",
390      'arg2'
391    ),
392    $ec_lists['user_ids']
393  );
394 
395  // Calculate users granted to duplication thanks to belonging to a
396  // certain group (in groups, level (friends, family, contacts),
397  // or user status (generic))
398  $r = pwg_query("
399    SELECT `arg2`
400    FROM `".EVNTCATS_TABLE."`
401    WHERE `code` IS NULL
402      AND `arg1` = 3
403      AND `arg2` IS NOT NULL
404    LIMIT 1;
405  ");
406  if (pwg_db_num_rows($r)) {
407    $types_entry_exists = true;
408    list($ec_lists['types_granted']) = pwg_db_fetch_row($r);
409  }
410  else {
411    $types_entry_exists = false;
412    $ec_lists['types_granted'] = 0;
413  }
414 
415  return $types_entry_exists;
416}
417
418/*
419 * build_ec_lists()
420 * builds the main array variable contaning all informations for the plugin
421 *
422 * @param
423 *   no parameter passed, the main material on which works the function, is
424 *   the global array variable $ec_lists.
425 * @return
426 *   (no return value)
427 */
428function build_ec_lists() {
429 
430  // Construction of $ec_lists['add_pages'] array var
431  build_ec_addp();
432 
433  // Construction of $ec_lists['categories'] array var
434  build_ec_categories(true);
435 
436  // Construction of $ec_lists['user_ids'] array var
437  build_ec_userids();
438 
439  // Construction of $ec_lists['ec_table'] array var
440  build_ec_table();
441}
442
443// +-----------------------------------------------------------------------+
444// | Duplication analysis functions                                        |
445// +-----------------------------------------------------------------------+
446
447/*
448 * build_dup_arrays($append_tpl = false)
449 * builds arrays telling which accounts are allowed to display a duplicate
450 * account link. Returns an array of all the user ids allowed to duplicate.
451 *
452 * @param
453 *   $append_tpl : tells if $template must be appended with built arrays
454 * @return
455 *   array of all the user ids allowed to duplicate
456 */
457function build_dup_arrays($append_tpl = false) {
458  global $template, $ec_lists, $conf;
459 
460  // A lot of below code has simply been copied from file cat_perm.php .
461  // Many thanks to people who wrote it !
462 
463  build_dup_groups();
464 
465  $users_granted_ids = array();
466 
467  $users_granted_thks_gen_ids = array();
468  if ($ec_gen_granted = (($ec_lists['types_granted'] & 8) != 0)) {
469    $users_granted_thks_gen_ids = ec_order_by_name(
470      array_diff(
471        array_from_query("
472          SELECT `user_id`
473          FROM `".USER_INFOS_TABLE."`
474          WHERE `status` = 'generic'
475            AND `user_id` > 2;",
476          'user_id'
477        ),
478        $ec_lists['users_granted_direct_ids']
479      ),
480      $ec_lists['user_ids']
481    );
482    foreach ($users_granted_thks_gen_ids as $user_id)
483     $users_granted_ids[$user_id] = l10n('user_status_generic');
484  }
485
486  $types = array(
487    '1' => l10n('Level 1'),
488    '2' => l10n('Level 2'),
489    '4' => l10n('Level 4'),
490  );
491  $types_granted_ids = array();
492  $users_granted_thks_types_ids = array();
493  if (($ec_lists['types_granted'] & 7) != 0) {
494    if (($ec_lists['types_granted'] & 1) != 0) $types_granted_ids[] = '1';
495    if (($ec_lists['types_granted'] & 2) != 0) $types_granted_ids[] = '2';
496    if (($ec_lists['types_granted'] & 4) != 0) $types_granted_ids[] = '4';
497    if (count($types_granted_ids) > 0) {
498      $user_granted_from_type = array();
499      $result = pwg_query("
500        SELECT `user_id`, `level`
501        FROM `".USER_INFOS_TABLE."`
502        WHERE `level` IN (".implode(',', $types_granted_ids).")
503          AND `user_id` > 2;
504      ");
505      while ($row = pwg_db_fetch_assoc($result)) {
506        if (!isset($user_granted_from_type[$row['level']])) {
507          $user_granted_from_type[$row['level']] = array();
508        }
509        $user_granted_from_type[$row['level']][] = $row['user_id'];
510      }
511      $user_granted_by_type_ids = array();
512      foreach ($user_granted_from_type as $type_users)
513       $user_granted_by_type_ids = array_merge(
514        $user_granted_by_type_ids,
515        $type_users
516       );
517      $users_granted_thks_types_ids = ec_order_by_name(
518        array_diff(
519          array_unique($user_granted_by_type_ids),
520          $ec_lists['users_granted_direct_ids']
521        ),
522        $ec_lists['user_ids']
523      );
524      foreach ($users_granted_thks_types_ids as $user_id)
525       foreach ($user_granted_from_type as $type_id => $type_users) {
526        if (in_array($user_id, $type_users)) {
527          $users_granted_ids[$user_id]= $types[$type_id];
528          break;
529        }
530       }
531    }
532  }
533
534  $users_granted_thks_groups_ids = array();
535  if (count($ec_lists['groups_granted_ids']) > 0) {
536    $granted_groups = array();
537
538    $result = pwg_query("
539      SELECT `user_id`, `group_id`
540      FROM `".USER_GROUP_TABLE."`
541      WHERE `group_id` IN (".implode(',', $ec_lists['groups_granted_ids']).")
542        AND `user_id` > 2;
543    ");
544    while ($row = pwg_db_fetch_assoc($result)) {
545      if (!isset($granted_groups[$row['group_id']])) {
546        $granted_groups[$row['group_id']] = array();
547      }
548      $granted_groups[$row['group_id']][] = $row['user_id'];
549    }
550   
551    $user_granted_by_group_ids = array();
552   
553    foreach ($granted_groups as $group_users)
554     $user_granted_by_group_ids = array_merge(
555      $user_granted_by_group_ids,
556      $group_users
557     );
558    $users_granted_thks_groups_ids = ec_order_by_name(
559      array_diff(
560        array_unique($user_granted_by_group_ids),
561        $ec_lists['users_granted_direct_ids']
562      ),
563      $ec_lists['user_ids']
564    );
565    foreach ($users_granted_thks_groups_ids as $user_id)
566     foreach ($granted_groups as $group_id => $group_users)
567      if (in_array($user_id, $group_users)) {
568        $users_granted_ids[$user_id]= $ec_lists['groups'][$group_id];
569        break;
570      }
571   
572  }
573
574  if ($append_tpl) {
575    $users_denied_ids = ec_order_by_name(
576      array_diff(
577        array_keys($ec_lists['user_ids']),
578        $users_granted_thks_gen_ids,
579        $users_granted_thks_types_ids,
580        $users_granted_thks_groups_ids,
581        $ec_lists['users_granted_direct_ids']
582      ),
583      $ec_lists['user_ids']
584    );
585   
586    foreach ($users_granted_ids as $u => $g) $template->append(
587      'user_granted_indirects',
588      array(
589        'USER'  => $ec_lists['user_ids'][$u],
590        'GROUP' => $g
591      )
592    );
593   
594    $template->assign('all_groups', $ec_lists['groups']);
595    $template->assign('groups_granted_ids', $ec_lists['groups_granted_ids']);
596    $template->assign('groups_denied_ids', ec_order_by_name(
597      array_diff(
598        array_keys($ec_lists['groups']),
599        $ec_lists['groups_granted_ids']
600      ),
601      $ec_lists['groups']
602    ));
603    $template->assign('ec_gen_granted', $ec_gen_granted);
604    $template->assign('all_types', $types);
605    $template->assign('types_granted_ids', $types_granted_ids);
606    $template->assign('types_denied_ids', ec_order_by_name(
607      array_diff(array_keys($types), $types_granted_ids), $types
608    ));
609    $template->assign('all_users', $ec_lists['user_ids']);
610    $template->assign(
611      'users_granted_direct_ids',
612      $ec_lists['users_granted_direct_ids']
613    );
614    $template->assign('users_denied_ids', $users_denied_ids);
615  }
616  $users_granted_ids = array_merge(
617    array_keys($users_granted_ids),
618    $ec_lists['users_granted_direct_ids']
619  );
620 
621  // Returns an array which values are all the user_ids allowed to display a
622  // "duplicate" link. The keys of this array are strange (for direct allowed
623  // users, keys are usernames), but should not used
624  return $users_granted_ids;
625}
626
627/*
628 * dup_allowed($user_id)
629 * returns true if the user_id is allowed to display a duplicate link
630 *
631 * @param
632 *   $user_id : the user_id
633 * @return
634 *   true if the user_id is allowed to display a duplicate link
635 */
636function dup_allowed($user_id) {
637  return in_array($user_id, build_dup_arrays());
638}
639
640?>
Note: See TracBrowser for help on using the repository browser.