[ Index ]
 

Code source de GeekLog 1.4.1

Accédez au Source d'autres logiciels libres

title

Body

[fermer]

/system/ -> lib-security.php (source)

   1  <?php
   2  
   3  /* Reminder: always indent with 4 spaces (no tabs). */
   4  // +---------------------------------------------------------------------------+
   5  // | Geeklog 1.4                                                               |
   6  // +---------------------------------------------------------------------------+
   7  // | lib-security.php                                                          |
   8  // |                                                                           |
   9  // | Geeklog security library.                                                 |
  10  // +---------------------------------------------------------------------------+
  11  // | Copyright (C) 2000-2006 by the following authors:                         |
  12  // |                                                                           |
  13  // | Authors: Tony Bibbs       - tony@tonybibbs.com                            |
  14  // |          Mark Limburg     - mlimburg@users.sourceforge.net                |
  15  // |          Vincent Furia    - vmf@abtech.org                                |
  16  // |          Michael Jervis   - mike@fuckingbrit.com                          |
  17  // +---------------------------------------------------------------------------+
  18  // |                                                                           |
  19  // | This program is free software; you can redistribute it and/or             |
  20  // | modify it under the terms of the GNU General Public License               |
  21  // | as published by the Free Software Foundation; either version 2            |
  22  // | of the License, or (at your option) any later version.                    |
  23  // |                                                                           |
  24  // | This program is distributed in the hope that it will be useful,           |
  25  // | but WITHOUT ANY WARRANTY; without even the implied warranty of            |
  26  // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
  27  // | GNU General Public License for more details.                              |
  28  // |                                                                           |
  29  // | You should have received a copy of the GNU General Public License         |
  30  // | along with this program; if not, write to the Free Software Foundation,   |
  31  // | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
  32  // |                                                                           |
  33  // +---------------------------------------------------------------------------+
  34  //
  35  // $Id: lib-security.php,v 1.55 2006/10/24 08:09:50 ospiess Exp $
  36  
  37  /**
  38  * This is the security library for Geeklog.  This is used to implement Geeklog's
  39  * *nix-style security system.
  40  *
  41  * Programming notes:  For items you need security on you need the following for
  42  * each record in your database:
  43  * owner_id        | mediumint(8)
  44  * group_id        | mediumint(8)
  45  * perm_owner      | tinyint(1) unsigned
  46  * perm_group      | tinyint(1) unsigned
  47  * perm_members    | tinyint(1) unsigned
  48  * perm_anon       | tinyint(1) unsigned
  49  *
  50  * For display one function can handle most needs:
  51  * function SEC_hasAccess($owner_id,$group_id,$perm_owner,$perm_group,$perm_members,$perm_anon)
  52  * A call to this function will allow you to determine if the current user should see the item.
  53  *
  54  * For the admin screen several functions will make life easier:
  55  * function SEC_getPermissionsHTML($perm_owner,$perm_group,$perm_members,$perm_anon)
  56  * This function displays the permissions widget with arrays for each permission
  57  * function SEC_getPermissionValues($perm_owner,$perm_group,$perm_members,$perm_anon)
  58  * This function takes the permissions from the previous function and converts them into
  59  * an integer for saving back to the database.
  60  *
  61  */
  62  
  63  // Turn this on go get various debug messages from the code in this library
  64  $_SEC_VERBOSE = false;
  65  
  66  if (strpos ($_SERVER['PHP_SELF'], 'lib-security.php') !== false) {
  67      die ('This file can not be used on its own!');
  68  }
  69  
  70  /* Constants for acount stats */
  71  define('USER_ACCOUNT_DISABLED', 0); // Account is banned/disabled
  72  define('USER_ACCOUNT_AWAITING_ACTIVATION', 1); // Account awaiting user to login.
  73  define('USER_ACCOUNT_AWAITING_APPROVAL', 2); // Account awaiting moderator approval
  74  define('USER_ACCOUNT_ACTIVE', 3); // active account
  75  
  76  /**
  77  * Returns the groups a user belongs to
  78  *
  79  * This is part of the GL security implementation.  This function returns
  80  * all the groups a user belongs to.  This function is called recursively
  81  * as groups can belong to other groups
  82  *
  83  * Note: this is an expensive function -- if you are concerned about speed it should only
  84  *       be used once at the beginning of a page.  The resulting array $_GROUPS can then be
  85  *       used through out the page.
  86  *
  87  * @return array Array of group ID's user belongs to
  88  *
  89  * @param        int     $uid            User ID to get information for. If empty current user.
  90  * @return    array    Associative Array grp_name -> ug_main_grp_id
  91  *
  92  */
  93  function SEC_getUserGroups($uid='')
  94  {
  95      global $_TABLES, $_USER, $_SEC_VERBOSE;
  96  
  97      if ($_SEC_VERBOSE) {
  98          COM_errorLog("****************in getusergroups(uid=$uid,usergroups=$usergroups,cur_grp_id=$cur_grp_id)***************",1);
  99      }
 100  
 101      $groups = array();
 102  
 103      if (empty($uid)) {
 104          if (empty($_USER['uid'])) {
 105              $uid = 1;
 106          } else {
 107              $uid = $_USER['uid'];
 108          }
 109      }
 110  
 111      $result = DB_query("SELECT ug_main_grp_id,grp_name FROM {$_TABLES["group_assignments"]},{$_TABLES["groups"]}"
 112              . " WHERE grp_id = ug_main_grp_id AND ug_uid = $uid",1);
 113  
 114      if ($result == -1) {
 115          return $groups;
 116      }
 117  
 118      $nrows = DB_numRows($result);
 119  
 120      if ($_SEC_VERBOSE) {
 121          COM_errorLog("got $nrows rows",1);
 122      }
 123  
 124      while ($nrows > 0) {
 125          $cgroups = array();
 126  
 127          for ($i = 1; $i <= $nrows; $i++) {
 128              $A = DB_fetchArray($result);
 129  
 130              if ($_SEC_VERBOSE) {
 131                  COM_errorLog('user is in group ' . $A['grp_name'],1);
 132              }
 133              if (!in_array($A['ug_main_grp_id'], $groups)) {
 134                  array_push($cgroups, $A['ug_main_grp_id']);
 135                  $groups[$A['grp_name']] = $A['ug_main_grp_id'];
 136              }
 137          }
 138  
 139          if (sizeof ($cgroups) > 0) {
 140              $glist = join(',', $cgroups);
 141              $result = DB_query("SELECT ug_main_grp_id,grp_name FROM {$_TABLES["group_assignments"]},{$_TABLES["groups"]}"
 142                      . " WHERE grp_id = ug_main_grp_id AND ug_grp_id IN ($glist)",1);
 143              $nrows = DB_numRows($result);
 144          } else {
 145              $nrows = 0;
 146          }
 147      }
 148  
 149      ksort($groups);
 150  
 151      if ($_SEC_VERBOSE) {
 152          COM_errorLog("****************leaving getusergroups(uid=$uid)***************",1);
 153      }
 154  
 155      return $groups;
 156  }
 157  
 158  /**
 159    * Checks to see if a user has admin access to the "Remote Users" group
 160    * Admin users will probably not be members, but, User Admin, Root, and
 161    * group admin will have access to it. However, we can not be sure what
 162    * the group id for "Remote User" group is, because it's a later static
 163    * group, and upgraded systems could have it in any id slot.
 164    *
 165    * @param      groupid     int     The id of a group, which might be the remote users group
 166    * @param      groups      array   Array of group ids the user has access to.
 167    * @return     boolean
 168    */
 169  function SEC_groupIsRemoteUserAndHaveAccess($groupid, $groups)
 170  {
 171      global $_TABLES, $_CONF;
 172      if(!isset($_CONF['remote_users_group_id']))
 173      {
 174          $result = DB_Query("SELECT grp_id FROM {$_TABLES['groups']} WHERE grp_name='Remote Users'");
 175          if( $result )
 176          {
 177              $row = DB_fetchArray( $result );
 178              $_CONF['remote_users_group_id'] = $row['grp_id'];
 179          }
 180      }
 181      if( $groupid == $_CONF['remote_users_group_id'] )
 182      {
 183          if( in_array( 1, $groups ) || // root
 184              in_array( 9, $groups ) || // user admin
 185              in_array( 11, $groups ) // Group admin
 186            )
 187          {
 188              return true;
 189          } else {
 190              return false;
 191          }
 192      } else {
 193          return false;
 194      }
 195  }
 196  
 197  /**
 198  * Determines if user belongs to specified group
 199  *
 200  * This is part of the Geeklog security implementation. This function
 201  * looks up whether a user belongs to a specified group
 202  *
 203  * @param        string      $grp_to_verify      Group we want to see if user belongs to
 204  * @param        int         $uid                ID for user to check. If empty current user.
 205  * @param        string      $cur_grp_id         NOT USED Current group we are working with in hierarchy
 206  * @return       boolean     true if user is in group, otherwise false
 207  *
 208  */
 209  function SEC_inGroup($grp_to_verify,$uid='',$cur_grp_id='')
 210  {
 211      global $_TABLES, $_USER, $_SEC_VERBOSE, $_GROUPS;
 212  
 213      if (empty ($uid)) {
 214          if (empty ($_USER['uid'])) {
 215              $uid = 1;
 216          } else {
 217              $uid = $_USER['uid'];
 218          }
 219      }
 220  
 221      if ((empty ($_USER['uid']) && ($uid == 1)) || ($uid == $_USER['uid'])) {
 222          if (empty ($_GROUPS)) {
 223              $_GROUPS = SEC_getUserGroups ($uid);
 224          }
 225          $groups = $_GROUPS;
 226      } else {
 227          $groups = SEC_getUserGroups ($uid);
 228      }
 229  
 230      if (is_numeric($grp_to_verify)) {
 231          if (in_array($grp_to_verify, $groups)) {
 232             return true;
 233          } else {
 234             return false;
 235          }
 236      } else {
 237          if (!empty($groups[$grp_to_verify])) {
 238              return true;
 239          } else {
 240              return false;
 241          }
 242     }
 243  }
 244  
 245  /**
 246  * Determines if current user is a moderator of any kind
 247  *
 248  * Checks to see if this user is a moderator for any of the GL features OR
 249  * GL plugins
 250  *
 251  * @return   boolean     returns if user has any .moderate rights
 252  *
 253  */
 254  function SEC_isModerator()
 255  {
 256      global $_USER,$_RIGHTS;
 257  
 258      // Loop through GL core rights.
 259      for ($i = 0; $i < count($_RIGHTS); $i++) {
 260          if (stristr($_RIGHTS[$i],'.moderate')) {
 261              return true;
 262          }
 263      }
 264  
 265      // If we get this far they are not a Geeklog moderator
 266      // So, let's return if they're a plugin moderator
 267  
 268      return PLG_isModerator();
 269  }
 270  
 271  /**
 272  * Checks to see if current user has access to a topic
 273  *
 274  * Checks to see if current user has access to a topic
 275  *
 276  * @param        string      $tid        ID for topic to check on
 277  * @return       int     returns 3 for read/edit 2 for read only 0 for no access
 278  *
 279  */
 280  function SEC_hasTopicAccess($tid)
 281  {
 282      global $_TABLES;
 283  
 284      if (empty($tid)) {
 285          return 0;
 286      }
 287  
 288      $result = DB_query("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['topics']} WHERE tid = '$tid'");
 289      $A = DB_fetchArray($result);
 290  
 291      return SEC_hasAccess($A['owner_id'],$A['group_id'],$A['perm_owner'],$A['perm_group'],$A['perm_members'],$A['perm_anon']);
 292  }
 293  
 294  /**
 295  * Checks if current user has access to the given object
 296  *
 297  * This function takes the access info from a Geeklog object
 298  * and let's us know if they have access to the object
 299  * returns 3 for read/edit, 2 for read only and 0 for no
 300  * access
 301  *
 302  * @param        int     $owner_id       ID of the owner of object
 303  * @param        int     $group_id       ID of group object belongs to
 304  * @param        int     $perm_owner     Permissions the owner has
 305  * @param        int     $perm_group     Permissions the gorup has
 306  * @param        int     $perm_members   Permissions logged in members have
 307  * @param        int     $perm_anon      Permissions anonymous users have
 308  * @return       int     returns 3 for read/edit 2 for read only 0 for no access
 309  *
 310  */
 311  function SEC_hasAccess($owner_id,$group_id,$perm_owner,$perm_group,$perm_members,$perm_anon)
 312  {
 313      global $_USER;
 314  
 315      // Cache current user id
 316      if (empty($_USER['uid'])) {
 317          $uid = 1;
 318      } else {
 319          $uid = $_USER['uid'];
 320      }
 321  
 322      // If user is in Root group then return full access
 323      if (SEC_inGroup('Root')) {
 324          return 3;
 325      }
 326  
 327      // If user is owner then return 1 now
 328      if ($uid == $owner_id) return $perm_owner;
 329  
 330      // Not private, if user is in group then give access
 331      if (SEC_inGroup($group_id)) {
 332          return $perm_group;
 333      } else {
 334          if ($uid == 1) {
 335              // This is an anonymous user, return it's rights
 336              return $perm_anon;
 337          } else {
 338              // This is a logged in member, return their rights
 339              return $perm_members;
 340          }
 341      }
 342  }
 343  
 344  /**
 345  * Checks if current user has rights to a feature
 346  *
 347  * Takes either a single feature or an array of features and returns
 348  * an array of whether the user has those rights
 349  *
 350  * @param        string|array        $features       Features to check
 351  * @param        string              $operator       Either 'and' or 'or'. Default is 'and'.  Used if checking more than one feature.
 352  * @return       boolean     Return true if current user has access to feature(s), otherwise false.
 353  *
 354  */
 355  function SEC_hasRights($features,$operator='AND')
 356  {
 357      global $_USER, $_RIGHTS, $_SEC_VERBOSE;
 358  
 359      if (strstr($features,',')) {
 360          $features = explode(',',$features);
 361      }
 362  
 363      if (is_array($features)) {
 364          // check all values passed
 365          for ($i = 0; $i < count($features); $i++) {
 366              if ($operator == 'OR') {
 367                  // OR operator, return as soon as we find a true one
 368                  if (in_array($features[$i],$_RIGHTS)) {
 369                      if ($_SEC_VERBOSE) {
 370                          COM_errorLog('SECURITY: user has access to ' . $features[$i],1);
 371                      }
 372                      return true;
 373                  }
 374              } else {
 375                  // this is an "AND" operator, bail if we find a false one
 376                  if (!in_array($features[$i],$_RIGHTS)) {
 377                      if ($_SEC_VERBOSE) {
 378                          COM_errorLog('SECURITY: user does not have access to ' . $features[$i],1);
 379                      }
 380                      return false;
 381                  }
 382              }
 383          }
 384  
 385          if ($operator == 'OR') {
 386              if ($_SEC_VERBOSE) {
 387                  COM_errorLog('SECURITY: user does not have access to ' . $features[$i],1);
 388              }
 389              return false;
 390                  } else {
 391              if ($_SEC_VERBOSE) {
 392                  COM_errorLog('SECURITY: user has access to ' . $features[$i],1);
 393              }
 394              return true;
 395          }
 396      } else {
 397          // Check the one value
 398          if ($_SEC_VERBOSE) {
 399              if (in_array($features,$_RIGHTS)) {
 400                  COM_errorLog('SECURITY: user has access to ' . $features,1);
 401              } else {
 402                  COM_errorLog('SECURITY: user does not have access to ' . $features,1);
 403              }
 404          }
 405          return in_array($features,$_RIGHTS);
 406      }
 407  }
 408  
 409  /**
 410  * Shows security control for an object
 411  *
 412  * This will return the HTML needed to create the security control see on the admin
 413  * screen for GL objects (i.e. stories, etc)
 414  *
 415  * @param        int     $perm_owner     Permissions the owner has 1 = edit 2 = read 3 = read/edit
 416  * @param        int     $perm_group     Permission the group has
 417  * @param        int     $perm_members   Permissions logged in members have
 418  * @param        int     $perm_anon      Permissions anonymous users have
 419  * @return       string  needed HTML (table) in HTML $perm_owner = array of permissions [edit,read], etc edit = 1 if permission, read = 2 if permission
 420  *
 421  */
 422  function SEC_getPermissionsHTML($perm_owner,$perm_group,$perm_members,$perm_anon)
 423  {
 424      global $LANG_ACCESS, $_CONF;
 425  
 426      $retval = '';
 427  
 428      $perm_templates = new Template($_CONF['path_layout'] . 'admin/common');
 429      $perm_templates->set_file(array('editor'=>'edit_permissions.thtml'));
 430  
 431      $perm_templates->set_var ('owner', $LANG_ACCESS['owner']);
 432      $perm_templates->set_var ('group', $LANG_ACCESS['group']);
 433      $perm_templates->set_var ('members', $LANG_ACCESS['members']);
 434      $perm_templates->set_var ('anonymous', $LANG_ACCESS['anonymous']);
 435  
 436      // Owner Permissions
 437      if ($perm_owner >= 2) {
 438          $perm_templates->set_var ('owner_r_checked',' checked="checked"');
 439      }
 440      if ($perm_owner == 3) {
 441          $perm_templates->set_var ('owner_e_checked',' checked="checked"');
 442      }
 443      // Group Permissions
 444      if ($perm_group >= 2) {
 445          $perm_templates->set_var ('group_r_checked',' checked="checked"');
 446      }
 447      if ($perm_group == 3) {
 448          $perm_templates->set_var ('group_e_checked',' checked="checked"');
 449      }
 450      // Member Permissions
 451      if ($perm_members == 2) {
 452          $perm_templates->set_var ('members_checked',' checked="checked"');
 453      }
 454      // Anonymous Permissions
 455      if ($perm_anon == 2) {
 456          $perm_templates->set_var ('anon_checked',' checked="checked"');
 457      }
 458  
 459      $perm_templates->parse('output','editor');
 460      $retval .= $perm_templates->finish($perm_templates->get_var('output'));
 461  
 462      return $retval;
 463  }
 464  
 465  /**
 466  * Gets everything a user has permissions to within the system
 467  *
 468  * This is part of the Geeklog security implmentation.  This function
 469  * will get all the permissions the current user has call itself recursively.
 470  *
 471  * @param        int     $grp_id     DO NOT USE (Used for reccursion) Current group function is working on
 472  * @uid        int    $uid        User to check, if empty current user.
 473  * @return       string   returns comma delimited list of features the user has access to
 474  *
 475  */
 476  function SEC_getUserPermissions($grp_id='',$uid='')
 477  {
 478      global $_TABLES, $_USER, $_SEC_VERBOSE, $_GROUPS;
 479  
 480      $retval = '';
 481  
 482      if ($_SEC_VERBOSE) {
 483          COM_errorLog("**********inside SEC_getUserPermissions(grp_id=$grp_id)**********",1);
 484      }
 485  
 486      // Get user ID if we don't already have it
 487      if (empty ($uid)) {
 488          if (empty ($_USER['uid'])) {
 489              $uid = 1;
 490          } else {
 491              $uid = $_USER['uid'];
 492          }
 493      }
 494  
 495      if ((empty ($_USER['uid']) && ($uid == 1)) || ($uid == $_USER['uid'])) {
 496          if (empty ($_GROUPS)) {
 497              $_GROUPS = SEC_getUserGroups ($uid);
 498          }
 499          $groups = $_GROUPS;
 500      } else {
 501          $groups = SEC_getUserGroups ($uid);
 502      }
 503  
 504      $glist = join(',', $groups);
 505      $result = DB_query("SELECT DISTINCT ft_name FROM {$_TABLES["access"]},{$_TABLES["features"]} "
 506                       . "WHERE ft_id = acc_ft_id AND acc_grp_id IN ($glist)");
 507  
 508      $nrows = DB_numrows($result);
 509      for ($j = 1; $j <= $nrows; $j++) {
 510          $A = DB_fetchArray($result);
 511          if ($_SEC_VERBOSE) {
 512              COM_errorLog('Adding right ' . $A['ft_name'] . ' in SEC_getUserPermissions',1);
 513          }
 514          $retval .= $A['ft_name'];
 515          if ($j < $nrows) {
 516              $retval .= ',';
 517          }
 518      }
 519  
 520      return $retval;
 521  }
 522  
 523  /**
 524  * Converts permissions to numeric values
 525  *
 526  * This function will take all permissions for an object and get the numeric value
 527  * that can then be used to save the database.
 528  *
 529  * @param        array       $perm_owner     Array of owner permissions  These arrays are set up by SEC_getPermissionsHTML
 530  * @param        array       $perm_group     Array of group permissions
 531  * @param        array       $perm_members   Array of member permissions
 532  * @param        array       $perm_anon      Array of anonymous user permissions
 533  * @return       array       returns numeric equivalent for each permissions array (2 = read, 3=edit/read)
 534  * @see    SEC_getPermissionsHTML
 535  * @see  SEC_getPermissionValue
 536  *
 537  */
 538  function SEC_getPermissionValues($perm_owner,$perm_group,$perm_members,$perm_anon)
 539  {
 540      global $_SEC_VERBOSE;
 541  
 542      if ($_SEC_VERBOSE) {
 543          COM_errorLog('**** Inside SEC_getPermissionValues ****', 1);
 544      }
 545  
 546      if (is_array($perm_owner)) {
 547          $perm_owner = SEC_getPermissionValue($perm_owner);
 548      } else {
 549          $perm_owner = 0;
 550      }
 551  
 552      if (is_array($perm_group)) {
 553          $perm_group = SEC_getPermissionValue($perm_group);
 554      } else {
 555          $perm_group = 0;
 556      }
 557  
 558      if (is_array($perm_members)) {
 559          $perm_members = SEC_getPermissionValue($perm_members);
 560      } else {
 561          $perm_members = 0;
 562      }
 563  
 564      if (is_array($perm_anon)) {
 565          $perm_anon = SEC_getPermissionValue($perm_anon);
 566      } else {
 567          $perm_anon = 0;
 568      }
 569  
 570      if ($_SEC_VERBOSE) {
 571          COM_errorlog('perm_owner = ' . $perm_owner, 1);
 572          COM_errorlog('perm_group = ' . $perm_group, 1);
 573          COM_errorlog('perm_member = ' . $perm_members, 1);
 574          COM_errorlog('perm_anon = ' . $perm_anon, 1);
 575          COM_errorLog('**** Leaving SEC_getPermissionValues ****', 1);
 576      }
 577  
 578      return array($perm_owner,$perm_group,$perm_members,$perm_anon);
 579  }
 580  
 581  /**
 582  * Converts permission array into numeric value
 583  *
 584  * This function converts an array of permissions for either
 585  * the owner/group/members/anon and returns the numeric
 586  * equivalent.  This is typically called by the admin screens
 587  * to prepare the permissions to be save to the database
 588  *
 589  * @param        array       $perm_x     Array of permission values
 590  * @return       int         integer representation of a permission array 2 = read 3 = edit/read
 591  * @see SEC_getPermissionValues
 592  *
 593  */
 594  function SEC_getPermissionValue($perm_x)
 595  {
 596      global $_SEC_VERBOSE;
 597  
 598      if ($_SEC_VERBOSE) {
 599          COM_errorLog('**** Inside SEC_getPermissionValue ***', 1);
 600      }
 601  
 602      $retval = 0;
 603  
 604      for ($i = 1; $i <= sizeof($perm_x); $i++) {
 605          if ($_SEC_VERBOSE) {
 606              COM_errorLog("perm_x[$i] = " . current($perm_x), 1);
 607          }
 608          $retval = $retval + current($perm_x);
 609          next($perm_x);
 610      }
 611  
 612      // if they have edit rights, assume read rights
 613      if ($retval == 1) {
 614          $retval = 3;
 615      }
 616  
 617      if ($_SEC_VERBOSE) {
 618          COM_errorLog("Got $retval permission value", 1);
 619          COM_errorLog('**** Leaving SEC_getPermissionValue ***', 1);
 620      }
 621  
 622      return $retval;
 623  }
 624  
 625  /**
 626  * Return the group to a given feature.
 627  *
 628  * Scenario: We have a feature and we want to know from which group the user
 629  * got this feature. Always returns the lowest group ID, in case the feature
 630  * has been inherited from more than one group.
 631  *
 632  * @param    string  $feature    the feature, e.g 'story.edit'
 633  * @param    int     $uid        (optional) user ID
 634  * @return   int                 group ID or 0
 635  *
 636  */
 637  function SEC_getFeatureGroup ($feature, $uid = '')
 638  {
 639      global $_GROUPS, $_TABLES, $_USER;
 640  
 641      $ugroups = array ();
 642  
 643      if (empty ($uid)) {
 644          if (empty ($_USER['uid'])) {
 645              $uid = 1;
 646          } else {
 647              $uid = $_USER['uid'];
 648          }
 649      }
 650  
 651      if ((empty ($_USER['uid']) && ($uid == 1)) || ($uid == $_USER['uid'])) {
 652          if (empty ($_GROUPS)) {
 653              $_GROUPS = SEC_getUserGroups ($uid);
 654          }
 655          $ugroups = $_GROUPS;
 656      } else {
 657          $ugroups = SEC_getUserGroups ($uid);
 658      }
 659  
 660      $group = 0;
 661  
 662      $ft_id = DB_getItem ($_TABLES['features'], 'ft_id', "ft_name = '$feature'");
 663      if (($ft_id > 0) && (sizeof ($ugroups) > 0)) {
 664          $grouplist = implode (',', $ugroups);
 665          $result = DB_query ("SELECT acc_grp_id FROM {$_TABLES['access']} WHERE (acc_ft_id = $ft_id) AND (acc_grp_id IN ($grouplist)) ORDER BY acc_grp_id LIMIT 1");
 666          $A = DB_fetchArray ($result);
 667          if (isset ($A['acc_grp_id'])) {
 668              $group = $A['acc_grp_id'];
 669          }
 670      }
 671  
 672      return $group;
 673  }
 674  
 675  /**
 676  * Attempt to login a user.
 677  *
 678  * Checks a users username and password against the database. Returns
 679  * users status.
 680  *
 681  * @param    string  $username   who is logging in?
 682  * @param    string  $password   what they claim is their password
 683  * @param    int     $uid        This is an OUTPUT param, pass by ref,
 684  *                               sends back UID inside it.
 685  * @return   int                 user status, -1 for fail.
 686  *
 687  */
 688  function SEC_authenticate($username, $password, &$uid)
 689  {
 690      global $_TABLES, $LANG01, $_CONF;
 691  
 692      $result = DB_query( "SELECT status, passwd, email, uid FROM {$_TABLES['users']} WHERE username='$username' AND ((remoteservice is null) or (remoteservice = ''))" );
 693      $tmp = DB_error();
 694      $nrows = DB_numRows( $result );
 695  
 696      if(( $tmp == 0 ) && ( $nrows == 1 ))
 697      {
 698          $U = DB_fetchArray( $result );
 699          $uid = $U['uid'];
 700          if ($U['status'] == USER_ACCOUNT_DISABLED)
 701          {
 702              return USER_ACCOUNT_DISABLED; // banned, jump to here to save an md5 calc.
 703          } elseif ($U['passwd'] != md5( $password )) {
 704              return -1; // failed login
 705          } elseif ($U['status'] == USER_ACCOUNT_AWAITING_APPROVAL) {
 706              //awaiting approval, jump to msg.
 707              echo COM_refresh($_CONF['site_url'] . '/users.php?msg=70');
 708              exit;
 709          } elseif ($U['status'] == USER_ACCOUNT_AWAITING_ACTIVATION) {
 710              // Awaiting user activation, activate:
 711              DB_change($_TABLES['users'],'status',USER_ACCOUNT_ACTIVE,'username',$username);
 712              return USER_ACCOUNT_ACTIVE;
 713          } else {
 714              return $U['status']; // just return their status
 715          }
 716      }
 717      else
 718      {
 719          $tmp = $LANG01[32] . ": '" . $username . "'";
 720          COM_errorLog( $tmp, 1 );
 721          return -1;
 722      }
 723  }
 724  
 725  /**
 726  * Return the current user status for a user.
 727  *
 728  * @param    int  $userid   Valid uid value.
 729  * @return   int            user status, 0-3
 730  *
 731  */
 732  function SEC_checkUserStatus($userid)
 733  {
 734      global $_CONF, $_TABLES;
 735  
 736      // Check user status
 737      $status = DB_getItem($_TABLES['users'], 'status', "uid=$userid");
 738  
 739      // only do redirects if we aren't on users.php in a valid mode (logout or
 740      // default)
 741      if (strpos ($_SERVER['PHP_SELF'], 'users.php') === false)
 742      {
 743          $redirect = true;
 744      } else {
 745          if (($_REQUEST['mode'] == 'logout') || ($_REQUEST['mode'] == ''))
 746          {
 747              $redirect = false;
 748          } else {
 749              $redirect = true;
 750          }
 751      }
 752      if ($status == USER_ACCOUNT_AWAITING_ACTIVATION)
 753      {
 754          DB_change($_TABLES['users'], 'status', USER_ACCOUNT_ACTIVE, 'uid', $userid);
 755      } elseif ($status == USER_ACCOUNT_AWAITING_APPROVAL) {
 756          // If we aren't on users.php with a default action then go to it
 757          if ($redirect)
 758          {
 759              COM_accessLog("SECURITY: Attempted Cookie Session login from user awaiting approval $userid.");
 760              echo COM_refresh($_CONF['site_url'] . '/users.php?msg=70');
 761              exit;
 762          }
 763      } elseif ($status == USER_ACCOUNT_DISABLED) {
 764          if ($redirect)
 765          {
 766              COM_accessLog("SECURITY: Attempted Cookie Session login from banned user $userid.");
 767              echo COM_refresh($_CONF['site_url'] . '/users.php?msg=69');
 768              exit;
 769          }
 770      }
 771  }
 772  
 773  /**
 774    * Check to see if we can authenticate this user with a remote server
 775    *
 776    * A user has not managed to login localy, but has an @ in their user
 777    * name and we have enabled distributed authentication. Firstly, try to
 778    * see if we have cached the module that we used to authenticate them
 779    * when they signed up (i.e. they've actualy changed their password
 780    * elsewhere and we need to synch.) If not, then try to authenticate
 781    * them with /every/ authentication module. If this suceeds, create
 782    * a user for them.
 783    *
 784    * @param  string  $loginname Their username
 785    * @param  string  $passwd The password entered
 786    * @param  string  $server The server portion of $username
 787    * @param  string  $uid OUTPUT parameter, pass it by ref to get uid back.
 788    * @return int     user status, -1 for fail.
 789    */
 790  function SEC_remoteAuthentication(&$loginname, $passwd, $service, &$uid)
 791  {
 792      global $_TABLES, $_CONF;
 793  
 794      /* First try a local cached login */
 795      $remoteusername = addslashes($loginname);
 796      $result = DB_query("SELECT passwd, status, uid FROM {$_TABLES['users']} WHERE remoteusername='$remoteusername' AND remoteservice='$service'");
 797      $tmp = DB_error();
 798      $nrows = DB_numRows($result);
 799      if (($tmp == 0) && ($nrows == 1))
 800      {
 801          $U = DB_fetchArray($result);
 802          $uid = $U['uid'];
 803          $mypass = $U['passwd']; // also used to see if the user existed later.
 804          if ($mypass == md5($passwd))
 805          {
 806              /* Valid password for cached user, return status */
 807              return $U['status'];
 808          }
 809      }
 810  
 811  
 812      if (file_exists($_CONF['path_system'].'classes/authentication/'.$service.'.auth.class.php'))
 813      {
 814          require_once($_CONF['path_system'].'classes/authentication/'.$service.'.auth.class.php');
 815          $authmodule = new $service();
 816          if ($authmodule->authenticate($loginname, $passwd))
 817          {
 818              /* check to see if they have logged in before: */
 819              if (empty($mypass))
 820              {
 821                  // no such user, create them
 822  
 823                  //Check to see if their remoteusername is unique locally
 824                  $checkName = DB_getItem($_TABLES['users'],'username',"username='$remoteusername'");
 825                  if ($checkName != '')
 826                  {
 827                      // no, call custom function.
 828                      if (function_exists(custom_uniqueRemoteUsername))
 829                      {
 830                          $loginname = custom_uniqueRemoteUsername($loginname, $service);
 831                      }
 832                  }
 833                  USER_createAccount($loginname, $authmodule->email, md5($passwd), '', '', $remoteusername, $service);
 834                  $uid = DB_getItem ($_TABLES['users'], 'uid', "remoteusername = '$remoteusername' AND remoteservice='$service'");
 835                  // Store full remote account name:
 836                  $service = addslashes($service);
 837                  DB_Query("UPDATE {$_TABLES['users']} SET remoteusername='$remoteusername', remoteservice='$service', status=3 WHERE uid='$uid'");
 838                  // Add to remote users:
 839                  $remote_grp = DB_getItem ($_TABLES['groups'], 'grp_id',
 840                                                "grp_name='Remote Users'");
 841                  DB_query ("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id,ug_uid) VALUES ($remote_grp, $uid)");
 842                  return 3; // Remote auth precludes usersubmission,
 843                            // and integrates user activation, see?
 844              } else {
 845                  // user existed, update local password:
 846                  DB_Change($_TABLES['users'], 'passwd', md5($passwd), array('remoteusername','remoteservice'), array($remoteusername,$service));
 847                  // and return their status
 848                  return DB_getItem($_TABLES['users'], 'status', "remoteusername='$remoteusername' AND remoteservice='$service'");
 849              }
 850          } else {
 851              return -1;
 852          }
 853      } else {
 854          return -1;
 855      }
 856  }
 857  
 858  /**
 859    * Add user to a group
 860    *
 861    * work in progress
 862    *
 863    * Rather self explanitory shortcut function
 864    * Is this the right place for this, Dirk?
 865    *
 866    * @author Trinity L Bays <trinity93@steubentech.com>
 867    *
 868    * @param  string  $uid Their user id
 869    * @param  string  $gname The group name
 870    * @return bool    status, true or false.
 871    */
 872  function SEC_addUserToGroup($uid, $gname)
 873  {
 874      global $_TABLES, $_CONF;
 875  
 876      $remote_grp = DB_getItem ($_TABLES['groups'], 'grp_id', "grp_name='". $gname ."'");
 877      DB_query ("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id,ug_uid) VALUES ($remote_grp, $uid)");
 878  }
 879  
 880  /**
 881  * Set default permissions for an object
 882  *
 883  * @param    array   $A                  target array
 884  * @param    array   $use_permissions    permissions to set
 885  *
 886  */
 887  function SEC_setDefaultPermissions (&$A, $use_permissions = array ())
 888  {
 889      if (!is_array ($use_permissions) || (count ($use_permissions) != 4)) {
 890          $use_permissions = array (3, 2, 2, 2);
 891      }
 892  
 893      // sanity checks
 894      if (($use_permissions[0] > 3) || ($use_permissions[0] < 0) ||
 895              ($use_permissions[0] == 1)) {
 896          $use_permissions[0] = 3;
 897      }
 898      if (($use_permissions[1] > 3) || ($use_permissions[1] < 0) ||
 899              ($use_permissions[1] == 1)) {
 900          $use_permissions[1] = 2;
 901      }
 902      if (($use_permissions[2] != 2) && ($use_permissions[2] != 0)) {
 903          $use_permissions[2] = 2;
 904      }
 905      if (($use_permissions[3] != 2) && ($use_permissions[3] != 0)) {
 906          $use_permissions[3] = 2;
 907      }
 908  
 909      $A['perm_owner']   = $use_permissions[0];
 910      $A['perm_group']   = $use_permissions[1];
 911      $A['perm_members'] = $use_permissions[2];
 912      $A['perm_anon']    = $use_permissions[3];
 913  }
 914  
 915  
 916  /**
 917  * Common function used to build group access SQL
 918  *
 919  * @param   string  $clause    Optional parm 'WHERE' - default is 'AND'
 920  * @return  string  $groupsql  Formatted SQL string to be appended in calling script SQL statement
 921  */
 922  function SEC_buildAccessSql ($clause = 'AND')
 923  {
 924      global $_TABLES, $_USER;
 925  
 926      if (isset($_USER) AND $_USER['uid'] > 1) {
 927          $uid = $_USER['uid'];
 928      } else {
 929          $uid = 1;
 930      }
 931  
 932      $_GROUPS = SEC_getUserGroups($uid);
 933      $groupsql = '';
 934      if (count($_GROUPS) == 1) {
 935          $groupsql .= " $clause grp_access = '" . current($_GROUPS) ."'";
 936      } else {
 937          $groupsql .= " $clause grp_access IN (" . implode(',',array_values($_GROUPS)) .")";
 938      }
 939  
 940      return $groupsql;
 941  }
 942  
 943  /**
 944  * Remove a feature from the database entirely.
 945  *
 946  * This function can be used by plugins during uninstall.
 947  *
 948  * @param    string  $feature_name   name of the feature, e.g. 'foo.edit'
 949  * @param    bool    $logging        whether to log progress in error.log
 950  * @return   void
 951  *
 952  */
 953  function SEC_removeFeatureFromDB ($feature_name, $logging = false)
 954  {
 955      global $_TABLES;
 956  
 957      if (!empty ($feature_name)) {
 958          $feat_id = DB_getItem ($_TABLES['features'], 'ft_id',
 959                                 "ft_name = '$feature_name'");
 960          if (!empty ($feat_id)) {
 961              // Before removing the feature itself, remove it from all groups
 962              if ($logging) {
 963                  COM_errorLog ("Attempting to remove '$feature_name' rights from all groups", 1);
 964              }
 965              DB_delete ($_TABLES['access'], 'acc_ft_id', $feat_id);
 966              if ($logging) {
 967                  COM_errorLog ('...success', 1);
 968              }
 969  
 970              // now remove the feature itself
 971              if ($logging) {
 972                  COM_errorLog ("Attempting to remove the '$feature_name' feature", 1);
 973              }
 974              DB_delete ($_TABLES['features'], 'ft_id', $feat_id);
 975              if ($logging) {
 976                  COM_errorLog ('...success', 1);
 977              }
 978          } else if ($logging) {
 979              COM_errorLog ("SEC_removeFeatureFromDB: Feature '$feature_name' not found.");
 980          }
 981      }
 982  }
 983  
 984  /**
 985  * Create a group dropdown
 986  *
 987  * Creates the group dropdown menu that's used on pretty much every admin page
 988  *
 989  * @param    int     $group_id   current group id (to be selected)
 990  * @param    int     $access     access permission
 991  * @return   string              HTML for the dropdown
 992  *
 993  */
 994  function SEC_getGroupDropdown ($group_id, $access)
 995  {
 996      global $_TABLES;
 997  
 998      $groupdd = '';
 999  
1000      if ($access == 3) {
1001          $usergroups = SEC_getUserGroups ();
1002  
1003          $groupdd .= '<select name="group_id">' . LB;
1004          foreach ($usergroups as $ug_name => $ug_id) {
1005              $groupdd .= '<option value="' . $ug_id . '"';
1006              if ($group_id == $ug_id) {
1007                  $groupdd .= ' selected="selected"';
1008              }
1009              $groupdd .= '>' . $ug_name . '</option>' . LB;
1010          }
1011          $groupdd .= '</select>' . LB;
1012      } else {
1013          // They can't set the group then
1014          $groupdd .= DB_getItem ($_TABLES['groups'], 'grp_name',
1015                                  "grp_id = '$group_id'")
1016                   . '<input type="hidden" name="group_id" value="' . $group_id
1017                   . '">';
1018      }
1019  
1020      return $groupdd;
1021  }
1022  
1023  ?>


Généré le : Wed Nov 21 12:27:40 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics