source: trunk/admin/include/functions.php @ 635

Last change on this file since 635 was 635, checked in by plg, 19 years ago
  • on picture.php, related categories under the element are displayed in global_rank order
  • when adding a new virtual category, initializes its global_rank
  • bug fixed : in admin/cat_list, false next rank
  • in admin/cat_modify, complete directory is calculated only if category is not virtual
  • admin/picture_modify rewritten : graphically nearer to admin/cat_modify, virtual associations are back
  • update_category partially rewritten : take an array of categories in parameter, becomes optionnaly recursive, use the set_random_representant function, set a random representant for categories with elements and no representant
  • bug fixed : on a search results screen, elements belonging to more than 1 category were shown more than once
  • bug fixed : in admin/cat_modify, changing a value in a textefield and hitting enter was setting a new random representant
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2004 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2004-12-05 21:28:40 +0000 (Sun, 05 Dec 2004) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 635 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28include(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
29
30$tab_ext_create_TN = array ( 'jpg', 'png', 'JPG', 'PNG' );
31
32// is_image returns true if the given $filename (including the path) is a
33// picture according to its format and its extension.
34// As GD library can only generate pictures from jpeg and png files, if you
35// ask if the filename is an image for thumbnail creation (second parameter
36// set to true), the only authorized formats are jpeg and png.
37function is_image( $filename, $create_thumbnail = false )
38{
39  global $conf, $tab_ext_create_TN;
40
41  if (is_file($filename)
42      and in_array(get_extension($filename), $conf['picture_ext']))
43  {
44    $size = getimagesize( $filename );
45    // $size[2] == 1 means GIF
46    // $size[2] == 2 means JPG
47    // $size[2] == 3 means PNG
48    if ( !$create_thumbnail )
49    {
50      if ( in_array( get_extension( $filename ), $conf['picture_ext'] )
51           and ( $size[2] == 1 or $size[2] == 2 or $size[2] == 3 ) )
52      {
53        return true;
54      }
55    }
56    else
57    {
58      if ( in_array( get_extension( $filename ), $tab_ext_create_TN )
59           and ( $size[2] == 2 or $size[2] == 3 ) )
60      {
61        return true;
62      }
63    }
64  }
65  return false;
66}
67
68/**
69 * returns an array with all picture files according to $conf['file_ext']
70 *
71 * @param string $dir
72 * @return array
73 */
74function get_pwg_files($dir)
75{
76  global $conf;
77
78  $pictures = array();
79  if ($opendir = opendir($dir))
80  {
81    while ($file = readdir($opendir))
82    {
83      if (in_array(get_extension($file), $conf['file_ext']))
84      {
85        array_push($pictures, $file);
86      }
87    }
88  }
89  return $pictures;
90}
91
92/**
93 * returns an array with all thumbnails according to $conf['picture_ext']
94 * and $conf['prefix_thumbnail']
95 *
96 * @param string $dir
97 * @return array
98 */
99function get_thumb_files($dir)
100{
101  global $conf;
102
103  $prefix_length = strlen($conf['prefix_thumbnail']);
104 
105  $thumbnails = array();
106  if ($opendir = @opendir($dir.'/thumbnail'))
107  {
108    while ($file = readdir($opendir))
109    {
110      if (in_array(get_extension($file), $conf['picture_ext'])
111          and substr($file, 0, $prefix_length) == $conf['prefix_thumbnail'])
112      {
113        array_push($thumbnails, $file);
114      }
115    }
116  }
117  return $thumbnails;
118}
119
120/**
121 * returns an array with representative picture files of a directory
122 * according to $conf['picture_ext']
123 *
124 * @param string $dir
125 * @return array
126 */
127function get_representative_files($dir)
128{
129  global $conf;
130
131  $pictures = array();
132  if ($opendir = @opendir($dir.'/pwg_representative'))
133  {
134    while ($file = readdir($opendir))
135    {
136      if (in_array(get_extension($file), $conf['picture_ext']))
137      {
138        array_push($pictures, $file);
139      }
140    }
141  }
142  return $pictures;
143}
144
145function TN_exists( $dir, $file )
146{
147  global $conf;
148
149  $filename = get_filename_wo_extension( $file );
150  foreach ( $conf['picture_ext'] as $ext ) {
151    $test = $dir.'/thumbnail/'.$conf['prefix_thumbnail'].$filename.'.'.$ext;
152    if ( is_file ( $test ) )
153    {
154      return $ext;
155    }
156  }
157  return false;
158}
159       
160
161// The function delete_site deletes a site and call the function
162// delete_categories for each primary category of the site
163function delete_site( $id )
164{
165  // destruction of the categories of the site
166  $query = '
167SELECT id
168  FROM '.CATEGORIES_TABLE.'
169  WHERE site_id = '.$id.'
170;';
171  $result = pwg_query($query);
172  $category_ids = array();
173  while ($row = mysql_fetch_array($result))
174  {
175    array_push($category_ids, $row['id']);
176  }
177  delete_categories($category_ids);
178               
179  // destruction of the site
180  $query = '
181DELETE FROM '.SITES_TABLE.'
182  WHERE id = '.$id.'
183;';
184  pwg_query($query);
185}
186       
187
188// The function delete_categories deletes the categories identified by the
189// (numeric) key of the array $ids. It also deletes (in the database) :
190//    - all the elements of the category (delete_elements, see further)
191//    - all the links between elements and this category
192//    - all the restrictions linked to the category
193// The function works recursively.
194function delete_categories($ids)
195{
196  global $counts;
197
198  if (count($ids) == 0)
199  {
200    return;
201  }
202 
203  // destruction of all the related elements
204  $query = '
205SELECT id
206  FROM '.IMAGES_TABLE.'
207  WHERE storage_category_id IN ('.implode(',', $ids).')
208;';
209  $result = pwg_query($query);
210  $element_ids = array();
211  while ($row = mysql_fetch_array($result))
212  {
213    array_push($element_ids, $row['id']);
214  }
215  delete_elements($element_ids);
216
217  // destruction of the links between images and this category
218  $query = '
219DELETE FROM '.IMAGE_CATEGORY_TABLE.'
220  WHERE category_id IN ('.implode(',', $ids).')
221;';
222  pwg_query($query);
223
224  // destruction of the access linked to the category
225  $query = '
226DELETE FROM '.USER_ACCESS_TABLE.'
227  WHERE cat_id IN ('.implode(',', $ids).')
228;';
229  pwg_query($query);
230  $query = '
231DELETE FROM '.GROUP_ACCESS_TABLE.'
232  WHERE cat_id IN ('.implode(',', $ids).')
233;';
234  pwg_query($query);
235
236  // destruction of the sub-categories
237  $query = '
238SELECT id
239  FROM '.CATEGORIES_TABLE.'
240  WHERE id_uppercat IN ('.implode(',', $ids).')
241;';
242  $result = pwg_query($query);
243  $subcat_ids = array();
244  while($row = mysql_fetch_array($result))
245  {
246    array_push($subcat_ids, $row['id']);
247  }
248  if (count($subcat_ids) > 0)
249  {
250    delete_categories($subcat_ids);
251  }
252
253  // destruction of the category
254  $query = '
255DELETE FROM '.CATEGORIES_TABLE.'
256  WHERE id IN ('.implode(',', $ids).')
257;';
258  pwg_query($query);
259
260  if (isset($counts['del_categories']))
261  {
262    $counts['del_categories']+= count($ids);
263  }
264}
265
266// The function delete_elements deletes the elements identified by the
267// (numeric) values of the array $ids. It also deletes (in the database) :
268//    - all the comments related to elements
269//    - all the links between categories and elements
270//    - all the favorites associated to elements
271function delete_elements($ids)
272{
273  global $counts;
274
275  if (count($ids) == 0)
276  {
277    return;
278  }
279 
280  // destruction of the comments on the image
281  $query = '
282DELETE FROM '.COMMENTS_TABLE.'
283  WHERE image_id IN (
284'.wordwrap(implode(', ', $ids), 80, "\n").')
285;';
286  pwg_query($query);
287
288  // destruction of the links between images and this category
289  $query = '
290DELETE FROM '.IMAGE_CATEGORY_TABLE.'
291  WHERE image_id IN (
292'.wordwrap(implode(', ', $ids), 80, "\n").')
293;';
294  pwg_query($query);
295
296  // destruction of the favorites associated with the picture
297  $query = '
298DELETE FROM '.FAVORITES_TABLE.'
299  WHERE image_id IN (
300'.wordwrap(implode(', ', $ids), 80, "\n").')
301;';
302  pwg_query($query);
303
304  // destruction of the rates associated to this element
305  $query = '
306DELETE FROM '.RATE_TABLE.'
307  WHERE element_id IN (
308'.wordwrap(implode(', ', $ids), 80, "\n").')
309;';
310  pwg_query($query);
311               
312  // destruction of the image
313  $query = '
314DELETE FROM '.IMAGES_TABLE.'
315  WHERE id IN (
316'.wordwrap(implode(', ', $ids), 80, "\n").')
317;';
318  pwg_query($query);
319
320  if (isset($counts['del_elements']))
321  {
322    $counts['del_elements']+= count($ids);
323  }
324}
325
326// The delete_user function delete a user identified by the $user_id
327// It also deletes :
328//     - all the access linked to this user
329//     - all the links to any group
330//     - all the favorites linked to this user
331//     - all sessions linked to this user
332//     - all categories informations linked to this user
333function delete_user( $user_id )
334{
335  // destruction of the access linked to the user
336  $query = 'DELETE FROM '.PREFIX_TABLE.'user_access';
337  $query.= ' WHERE user_id = '.$user_id;
338  $query.= ';';
339  pwg_query( $query );
340
341  // destruction of the group links for this user
342  $query = 'DELETE FROM '.PREFIX_TABLE.'user_group';
343  $query.= ' WHERE user_id = '.$user_id;
344  $query.= ';';
345  pwg_query( $query );
346
347  // destruction of the favorites associated with the user
348  $query = 'DELETE FROM '.PREFIX_TABLE.'favorites';
349  $query.= ' WHERE user_id = '.$user_id;
350  $query.= ';';
351  pwg_query( $query );
352
353  // destruction of the sessions linked with the user
354  $query = 'DELETE FROM '.PREFIX_TABLE.'sessions';
355  $query.= ' WHERE user_id = '.$user_id;
356  $query.= ';';
357  pwg_query( $query );
358
359  // destruction of the user
360  $query = 'DELETE FROM '.USERS_TABLE;
361  $query.= ' WHERE id = '.$user_id;
362  $query.= ';';
363  pwg_query( $query );
364}
365
366// delete_group deletes a group identified by its $group_id.
367// It also deletes :
368//     - all the access linked to this group
369//     - all the links between this group and any user
370function delete_group( $group_id )
371{
372  // destruction of the access linked to the group
373  $query = 'DELETE FROM '.PREFIX_TABLE.'group_access';
374  $query.= ' WHERE group_id = '.$group_id;
375  $query.= ';';
376  pwg_query( $query );
377
378  // synchronize all users linked to the group
379  synchronize_group( $group_id );
380
381  // destruction of the users links for this group
382  $query = 'DELETE FROM '.PREFIX_TABLE.'user_group';
383  $query.= ' WHERE group_id = '.$group_id;
384  $query.= ';';
385  pwg_query( $query );
386
387  // destruction of the group
388  $query = 'DELETE FROM '.PREFIX_TABLE.'groups';
389  $query.= ' WHERE id = '.$group_id;
390  $query.= ';';
391  pwg_query( $query );
392}
393
394// The check_favorites function deletes all the favorites of a user if he is
395// not allowed to see them (the category or an upper category is restricted
396// or invisible)
397function check_favorites( $user_id )
398{
399  $query = 'SELECT status,forbidden_categories';
400  $query.= ' FROM '.USERS_TABLE;
401  $query.= ' WHERE id = '.$user_id;
402  $query.= ';';
403  $row = mysql_fetch_array( pwg_query( $query ) );
404  $status = $row['status'];
405  // retrieving all the restricted categories for this user
406  if ( isset( $row['forbidden_categories'] ) )
407    $restricted_cat = explode( ',', $row['forbidden_categories'] );
408  else
409    $restricted_cat = array();
410  // retrieving all the favorites for this user and comparing their
411  // categories to the restricted categories
412  $query = 'SELECT image_id FROM '.FAVORITES_TABLE;
413  $query.= ' WHERE user_id = '.$user_id;
414  $query.= ';';
415  $result = pwg_query ( $query );
416  while ( $row = mysql_fetch_array( $result ) )
417  {
418    // for each picture, we have to check all the categories it belongs
419    // to. Indeed if a picture belongs to category_1 and category_2 and that
420    // category_2 is not restricted to the user, he can have the picture as
421    // favorite.
422    $query = 'SELECT DISTINCT(category_id) as category_id';
423    $query.= ' FROM '.PREFIX_TABLE.'image_category';
424    $query.= ' WHERE image_id = '.$row['image_id'];
425    $query.= ';';
426    $picture_result = pwg_query( $query );
427    $picture_cat = array();
428    while ( $picture_row = mysql_fetch_array( $picture_result ) )
429    {
430      array_push( $picture_cat, $picture_row['category_id'] );
431    }
432    if ( count( array_diff( $picture_cat, $restricted_cat ) ) == 0 )
433    {
434      $query = 'DELETE FROM '.FAVORITES_TABLE;
435      $query.= ' WHERE image_id = '.$row['image_id'];
436      $query.= ' AND user_id = '.$user_id;
437      $query.= ';';
438      pwg_query( $query );
439    }
440  }
441}
442
443/**
444 * updates calculated informations about a set of categories : date_last and
445 * nb_images. It also verifies that the representative picture is really
446 * linked to the category. Optionnaly recursive.
447 *
448 * @param mixed category id
449 * @param boolean recursive
450 * @returns void
451 */
452function update_category($ids = 'all', $recursive = false)
453{
454  // retrieving all categories to update
455  $cat_ids = array();
456 
457  $query = '
458SELECT id
459  FROM '.CATEGORIES_TABLE;
460  if (is_array($ids))
461  {
462    if ($recursive)
463    {
464      foreach ($ids as $num => $id)
465      {
466        if ($num == 0)
467        {
468          $query.= '
469  WHERE ';
470        }
471        else
472        {
473          $query.= '
474  OR    ';
475        }
476        $query.= 'uppercats REGEXP \'(^|,)'.$id.'(,|$)\'';
477      }
478    }
479    else
480    {
481      $query.= '
482  WHERE id IN ('.implode(',', $ids).')';
483    }
484  }
485  $query.= '
486;';
487  $result = pwg_query( $query );
488  while ( $row = mysql_fetch_array( $result ) )
489  {
490    array_push($cat_ids, $row['id']);
491  }
492  $cat_ids = array_unique($cat_ids);
493
494  if (count($cat_ids) == 0)
495  {
496    return false;
497  }
498 
499  // calculate informations about categories retrieved
500  $query = '
501SELECT category_id,
502       COUNT(image_id) AS nb_images,
503       MAX(date_available) AS date_last
504  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id = image_id
505  WHERE category_id IN ('.implode(',', $cat_ids).')
506  GROUP BY category_id
507';
508  $result = pwg_query($query);
509  $datas = array();
510  while ( $row = mysql_fetch_array( $result ) )
511  {
512    array_push($datas, array('id' => $row['category_id'],
513                             'date_last' => $row['date_last'],
514                             'nb_images' => $row['nb_images']));
515  }
516  $fields = array('primary' => array('id'),
517                  'update'  => array('date_last', 'nb_images'));
518  mass_updates(CATEGORIES_TABLE, $fields, $datas);
519
520  $query = '
521UPDATE '.CATEGORIES_TABLE.'
522  SET representative_picture_id = NULL
523  WHERE nb_images = 0
524;';
525  pwg_query($query);
526 
527  if (count($cat_ids) > 0)
528  {
529    $categories = array();
530    // find all categories where the setted representative is not possible
531    $query = '
532SELECT id
533  FROM '.CATEGORIES_TABLE.' LEFT JOIN '.IMAGE_CATEGORY_TABLE.'
534    ON id = category_id AND representative_picture_id = image_id
535  WHERE representative_picture_id IS NOT NULL
536    AND id IN ('.implode(',', $cat_ids).')
537    AND category_id IS NULL
538;';
539    $result = pwg_query($query);
540    while ($row = mysql_fetch_array($result))
541    {
542      array_push($categories, $row['id']);
543    }
544    // find categories with elements and with no representant
545    $query = '
546SELECT id
547  FROM '.CATEGORIES_TABLE.'
548  WHERE representative_picture_id IS NULL
549    AND nb_images != 0
550;';
551    $result = pwg_query($query);
552    while ($row = mysql_fetch_array($result))
553    {
554      array_push($categories, $row['id']);
555    }
556
557    $categories = array_unique($categories);
558    set_random_representant($categories);
559  }
560}
561
562function check_date_format( $date )
563{
564  // date arrives at this format : DD/MM/YYYY
565  @list($day,$month,$year) = explode( '/', $date );
566  return @checkdate( $month, $day, $year );
567}
568
569function date_convert( $date )
570{
571  // date arrives at this format : DD/MM/YYYY
572  // It must be transformed in YYYY-MM-DD
573  list($day,$month,$year) = explode( '/', $date );
574  return $year.'-'.$month.'-'.$day;
575}
576
577function date_convert_back( $date )
578{
579  // date arrives at this format : YYYY-MM-DD
580  // It must be transformed in DD/MM/YYYY
581  if ( $date != '' )
582  {
583    list($year,$month,$day) = explode( '-', $date );
584    return $day.'/'.$month.'/'.$year;
585  }
586  else
587  {
588    return '';
589  }
590}
591
592// get_keywords returns an array with relevant keywords found in the string
593// given in argument. Keywords must be separated by comma in this string.
594// keywords must :
595//   - be longer or equal to 3 characters
596//   - not contain ', " or blank characters
597//   - unique in the string ("test,test" -> "test")
598function get_keywords( $keywords_string )
599{
600  $keywords = array();
601
602  $candidates = explode( ',', $keywords_string );
603  foreach ( $candidates as $candidate ) {
604    if ( strlen($candidate) >= 3 and !preg_match( '/(\'|"|\s)/', $candidate ) )
605      array_push( $keywords, $candidate );
606  }
607
608  return array_unique( $keywords );
609}
610
611/**
612 * returns an array with the ids of the restricted categories for the user
613 *
614 * Returns an array with the ids of the restricted categories for the
615 * user. If the $check_invisible parameter is set to true, invisible
616 * categorie are added to the restricted one in the array.
617 *
618 * @param int $user_id
619 * @param string $user_status
620 * @param bool $check_invisible
621 * @param bool $use_groups
622 * @return array
623 */
624function get_user_restrictions( $user_id, $user_status,
625                                $check_invisible, $use_groups = true )
626{
627  // 1. retrieving ids of private categories
628  $query = 'SELECT id FROM '.CATEGORIES_TABLE;
629  $query.= " WHERE status = 'private'";
630  $query.= ';';
631  $result = pwg_query( $query );
632  $privates = array();
633  while ( $row = mysql_fetch_array( $result ) )
634  {
635    array_push( $privates, $row['id'] );
636  }
637  // 2. retrieving all authorized categories for the user
638  $authorized = array();
639  // 2.1. retrieving authorized categories thanks to personnal user
640  //      authorization
641  $query = 'SELECT cat_id FROM '.USER_ACCESS_TABLE;
642  $query.= ' WHERE user_id = '.$user_id;
643  $query.= ';';
644  $result = pwg_query( $query );
645  while ( $row = mysql_fetch_array( $result ) )
646  {
647    array_push( $authorized, $row['cat_id'] );
648  }
649  // 2.2. retrieving authorized categories thanks to group authorization to
650  //      which the user is a member
651  if ( $use_groups )
652  {
653    $query = 'SELECT ga.cat_id';
654    $query.= ' FROM '.USER_GROUP_TABLE.' as ug';
655    $query.= ', '.GROUP_ACCESS_TABLE.' as ga';
656    $query.= ' WHERE ug.group_id = ga.group_id';
657    $query.= ' AND ug.user_id = '.$user_id;
658    $query.= ';';
659    $result = pwg_query( $query );
660    while ( $row = mysql_fetch_array( $result ) )
661    {
662      array_push( $authorized, $row['cat_id'] );
663    }
664    $authorized = array_unique( $authorized );
665  }
666
667  $forbidden = array();
668  foreach ( $privates as $private ) {
669    if ( !in_array( $private, $authorized ) )
670    {
671      array_push( $forbidden, $private );
672    }
673  }
674
675  if ( $check_invisible )
676  {
677    // 3. adding to the restricted categories, the invisible ones
678    if ( $user_status != 'admin' )
679    {
680      $query = 'SELECT id FROM '.CATEGORIES_TABLE;
681      $query.= " WHERE visible = 'false';";
682      $result = pwg_query( $query );
683      while ( $row = mysql_fetch_array( $result ) )
684      {
685        array_push( $forbidden, $row['id'] );
686      }
687    }
688  }
689  return array_unique( $forbidden );
690}
691
692/**
693 * updates the calculated data users.forbidden_categories, it includes
694 * sub-categories of the direct forbidden categories
695 *
696 * @param nt $user_id
697 * @return array
698 */
699function update_user_restrictions( $user_id )
700{
701  $restrictions = get_user_all_restrictions( $user_id );
702
703  // update the users.forbidden_categories in database
704  $query = 'UPDATE '.USERS_TABLE;
705  $query.= ' SET forbidden_categories = ';
706  if ( count( $restrictions ) > 0 )
707    $query.= "'".implode( ',', $restrictions )."'";
708  else
709    $query.= 'NULL';
710  $query .= ' WHERE id = '.$user_id;
711  $query.= ';';
712  pwg_query( $query );
713
714  return $restrictions;
715}
716
717/**
718 * returns all the restricted categories ids including sub-categories
719 *
720 * @param int $user_id
721 * @return array
722 */
723function get_user_all_restrictions( $user_id )
724{
725  global $page;
726 
727  $query = 'SELECT status';
728  $query.= ' FROM '.USERS_TABLE;
729  $query.= ' WHERE id = '.$user_id;
730  $query.= ';';
731  $row = mysql_fetch_array( pwg_query( $query ) );
732 
733  $base_restrictions=get_user_restrictions($user_id,$row['status'],true,true);
734
735  $restrictions = $base_restrictions;
736  foreach ( $base_restrictions as $category_id ) {
737    echo $category_id.' is forbidden to user '.$user_id.'<br />';
738    $restrictions =
739      array_merge( $restrictions,
740                   $page['plain_structure'][$category_id]['all_subcats_ids'] );
741  }
742
743  return array_unique( $restrictions );
744}
745
746// The function is_user_allowed returns :
747//      - 0 : if the category is allowed with this $restrictions array
748//      - 1 : if this category is not allowed
749//      - 2 : if an uppercat category is not allowed
750// Note : the restrictions array must represent ONLY direct forbidden
751// categories, not all forbidden categories
752function is_user_allowed( $category_id, $restrictions )
753{
754  if ( in_array( $category_id, $restrictions ) ) return 1;
755
756  $query = 'SELECT uppercats';
757  $query.= ' FROM '.CATEGORIES_TABLE;
758  $query.= ' WHERE id = '.$category_id;
759  $query.= ';';
760  $row = mysql_fetch_array( pwg_query( $query ) );
761  $uppercats = explode( ',', $row['uppercats'] );
762  foreach ( $uppercats as $category_id ) {
763    if ( in_array( $category_id, $restrictions ) ) return 2;
764  }
765
766  // no restriction found : the user is allowed to access this category
767  return 0;
768}
769
770/**
771 * returns an array containing sub-directories which can be a category
772 *
773 * directories nammed "thumbnail", "pwg_high" or "pwg_representative" are
774 * omitted
775 *
776 * @param string $basedir
777 * @return array
778 */
779function get_category_directories( $basedir )
780{
781  $sub_dirs = array();
782
783  if ( $opendir = opendir( $basedir ) )
784  {
785    while ( $file = readdir( $opendir ) )
786    {
787      if ($file != '.'
788          and $file != '..'
789          and $file != 'thumbnail'
790          and $file != 'pwg_high'
791          and $file != 'pwg_representative'
792          and is_dir($basedir.'/'.$file))
793      {
794        array_push( $sub_dirs, $file );
795      }
796    }
797  }
798  return $sub_dirs;
799}
800
801// my_error returns (or send to standard output) the message concerning the
802// error occured for the last mysql query.
803function my_error($header, $echo = true)
804{
805  $error = $header.'<span style="font-weight:bold;">N°= '.mysql_errno();
806  $error.= ' -->> '.mysql_error()."</span><br /><br />\n";
807  if ($echo)
808  {
809    echo $error;
810  }
811  else
812  {
813    return $error;
814  }
815}
816
817/**
818 * inserts multiple lines in a table
819 *
820 * @param string table_name
821 * @param array dbfields
822 * @param array inserts
823 * @return void
824 */
825function mass_inserts($table_name, $dbfields, $datas)
826{
827  // inserts all found categories
828  $query = '
829INSERT INTO '.$table_name.'
830  ('.implode(',', $dbfields).')
831   VALUES';
832  foreach ($datas as $insert_id => $insert)
833  {
834    $query.= '
835  ';
836    if ($insert_id > 0)
837    {
838      $query.= ',';
839    }
840    $query.= '(';
841    foreach ($dbfields as $field_id => $dbfield)
842    {
843      if ($field_id > 0)
844      {
845        $query.= ',';
846      }
847     
848      if (!isset($insert[$dbfield]) or $insert[$dbfield] == '')
849      {
850        $query.= 'NULL';
851      }
852      else
853      {
854        $query.= "'".$insert[$dbfield]."'";
855      }
856    }
857    $query.=')';
858  }
859  $query.= '
860;';
861  pwg_query($query);
862}
863
864/**
865 * updates multiple lines in a table
866 *
867 * @param string table_name
868 * @param array dbfields
869 * @param array datas
870 * @return void
871 */
872function mass_updates($tablename, $dbfields, $datas)
873{
874  // depending on the MySQL version, we use the multi table update or N
875  // update queries
876  $query = 'SELECT VERSION() AS version;';
877  $row = mysql_fetch_array(pwg_query($query));
878  if (count($datas) < 10 or version_compare($row['version'],'4.0.4') < 0)
879  {
880    // MySQL is prior to version 4.0.4, multi table update feature is not
881    // available
882    foreach ($datas as $data)
883    {
884      $query = '
885UPDATE '.$tablename.'
886  SET ';
887      foreach ($dbfields['update'] as $num => $key)
888      {
889        if ($num >= 1)
890        {
891          $query.= ",\n      ";
892        }
893        $query.= $key.' = ';
894        if (isset($data[$key]))
895        {
896          $query.= '\''.$data[$key].'\'';
897        }
898        else
899        {
900          $query.= 'NULL';
901        }
902      }
903      $query.= '
904  WHERE ';
905      foreach ($dbfields['primary'] as $num => $key)
906      {
907        if ($num > 1)
908        {
909          $query.= ' AND ';
910        }
911        $query.= $key.' = \''.$data[$key].'\'';
912      }
913      $query.= '
914;';
915      pwg_query($query);
916    }
917  }
918  else
919  {
920    // creation of the temporary table
921    $query = '
922DESCRIBE '.$tablename.'
923;';
924    $result = pwg_query($query);
925    $columns = array();
926    $all_fields = array_merge($dbfields['primary'], $dbfields['update']);
927    while ($row = mysql_fetch_array($result))
928    {
929      if (in_array($row['Field'], $all_fields))
930      {
931        $column = $row['Field'];
932        $column.= ' '.$row['Type'];
933        if (!isset($row['Null']) or $row['Null'] == '')
934        {
935          $column.= ' NOT NULL';
936        }
937        if (isset($row['Default']))
938        {
939          $column.= " default '".$row['Default']."'";
940        }
941        array_push($columns, $column);
942      }
943    }
944    $query = '
945CREATE TEMPORARY TABLE '.$tablename.'_temporary
946(
947'.implode(",\n", $columns).',
948PRIMARY KEY (id)
949)
950;';
951    pwg_query($query);
952    mass_inserts($tablename.'_temporary', $all_fields, $datas);
953    // update of images table by joining with temporary table
954    $query = '
955UPDATE '.$tablename.' AS t1, '.$tablename.'_temporary AS t2
956  SET '.implode("\n    , ",
957                array_map(
958                  create_function('$s', 'return "t1.$s = t2.$s";')
959                  , $dbfields['update'])).'
960  WHERE '.implode("\n    AND ",
961                array_map(
962                  create_function('$s', 'return "t1.$s = t2.$s";')
963                  , $dbfields['primary'])).'
964;';
965    pwg_query($query);
966    $query = '
967DROP TABLE '.$tablename.'_temporary
968;';
969    pwg_query($query);
970  }
971}
972
973/**
974 * updates the global_rank of categories under the given id_uppercat
975 *
976 * @param int id_uppercat
977 * @return void
978 */
979function update_global_rank($id_uppercat = 'all')
980{
981  $query = '
982SELECT id,rank
983  FROM '.CATEGORIES_TABLE.'
984;';
985  $result = pwg_query($query);
986  $ranks_array = array();
987  while ($row = mysql_fetch_array($result))
988  {
989    $ranks_array[$row['id']] = $row['rank'];
990  }
991
992  // which categories to update ?
993  $uppercats_array = array();
994
995  $query = '
996SELECT id,uppercats
997  FROM '.CATEGORIES_TABLE;
998  if (is_numeric($id_uppercat))
999  {
1000    $query.= '
1001  WHERE uppercats REGEXP \'(^|,)'.$id_uppercat.'(,|$)\'
1002    AND id != '.$id_uppercat.'
1003';
1004  }
1005  $query.= '
1006;';
1007  $result = pwg_query($query);
1008  while ($row = mysql_fetch_array($result))
1009  {
1010    $uppercats_array[$row['id']] =  $row['uppercats'];
1011  }
1012 
1013  $datas = array();
1014  foreach ($uppercats_array as $id => $uppercats)
1015  {
1016    $data = array();
1017    $data['id'] = $id;
1018    $global_rank = preg_replace('/(\d+)/e',
1019                                "\$ranks_array['$1']",
1020                                str_replace(',', '.', $uppercats));
1021    $data['global_rank'] = $global_rank;
1022    array_push($datas, $data);
1023  }
1024
1025  $fields = array('primary' => array('id'), 'update' => array('global_rank'));
1026  mass_updates(CATEGORIES_TABLE, $fields, $datas);
1027}
1028
1029/**
1030 * change the visible property on a set of categories
1031 *
1032 * @param array categories
1033 * @param string value
1034 * @return void
1035 */
1036function set_cat_visible($categories, $value)
1037{
1038  if (!in_array($value, array('true', 'false')))
1039  {
1040    return false;
1041  }
1042
1043  // unlocking a category => all its parent categories become unlocked
1044  if ($value == 'true')
1045  {
1046    $uppercats = array();
1047    $query = '
1048SELECT uppercats
1049  FROM '.CATEGORIES_TABLE.'
1050  WHERE id IN ('.implode(',', $categories).')
1051;';
1052    $result = pwg_query($query);
1053    while ($row = mysql_fetch_array($result))
1054    {
1055      $uppercats = array_merge($uppercats,
1056                               explode(',', $row['uppercats']));
1057    }
1058    $uppercats = array_unique($uppercats);
1059     
1060    $query = '
1061UPDATE '.CATEGORIES_TABLE.'
1062  SET visible = \'true\'
1063  WHERE id IN ('.implode(',', $uppercats).')
1064;';
1065    pwg_query($query);
1066  }
1067  // locking a category   => all its child categories become locked
1068  if ($value == 'false')
1069  {
1070    $subcats = get_subcat_ids($categories);
1071    $query = '
1072UPDATE '.CATEGORIES_TABLE.'
1073  SET visible = \'false\'
1074  WHERE id IN ('.implode(',', $subcats).')
1075;';
1076    pwg_query($query);
1077  }
1078}
1079
1080/**
1081 * change the status property on a set of categories : private or public
1082 *
1083 * @param array categories
1084 * @param string value
1085 * @return void
1086 */
1087function set_cat_status($categories, $value)
1088{
1089  if (!in_array($value, array('public', 'private')))
1090  {
1091    return false;
1092  }
1093
1094  // make public a category => all its parent categories become public
1095  if ($value == 'public')
1096  {
1097    $uppercats = array();
1098    $query = '
1099SELECT uppercats
1100  FROM '.CATEGORIES_TABLE.'
1101  WHERE id IN ('.implode(',', $categories).')
1102;';
1103    $result = pwg_query($query);
1104    while ($row = mysql_fetch_array($result))
1105    {
1106      $uppercats = array_merge($uppercats,
1107                               explode(',', $row['uppercats']));
1108    }
1109    $uppercats = array_unique($uppercats);
1110     
1111    $query = '
1112UPDATE '.CATEGORIES_TABLE.'
1113  SET status = \'public\'
1114  WHERE id IN ('.implode(',', $uppercats).')
1115;';
1116    pwg_query($query);
1117  }
1118  // make a category private => all its child categories become private
1119  if ($value == 'private')
1120  {
1121    $subcats = get_subcat_ids($categories);
1122    $query = '
1123UPDATE '.CATEGORIES_TABLE.'
1124  SET status = \'private\'
1125  WHERE id IN ('.implode(',', $subcats).')
1126;';
1127    pwg_query($query);
1128  }
1129}
1130
1131/**
1132 * set a new random representant to the categories
1133 *
1134 * @param array categories
1135 */
1136function set_random_representant($categories)
1137{
1138  $datas = array();
1139  foreach ($categories as $category_id)
1140  {
1141    $query = '
1142SELECT image_id
1143  FROM '.IMAGE_CATEGORY_TABLE.'
1144  WHERE category_id = '.$category_id.'
1145  ORDER BY RAND()
1146  LIMIT 0,1
1147;';
1148    list($representative) = mysql_fetch_array(pwg_query($query));
1149    $data = array('id' => $category_id,
1150                  'representative_picture_id' => $representative);
1151    array_push($datas, $data);
1152  }
1153
1154  $fields = array('primary' => array('id'),
1155                  'update' => array('representative_picture_id'));
1156  mass_updates(CATEGORIES_TABLE, $fields, $datas);
1157}
1158?>
Note: See TracBrowser for help on using the repository browser.