CoolFace
Apppublic

kenken999/php

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
security.php2999 linesDownload Raw Back to classes
1<?php2class Security3{4	public static function processPageSecurity( $table, $permission, $ajaxMode = false, $message = '' )5	{6		if( Security::checkPagePermissions( $table, $permission ) )7			return true;8 9		if( $ajaxMode )10		{11			Security::sendPermissionError( $message );12			return false;13		}14		// The user is logged in but lacks necessary permissions15		// redirect to Menu.16		if( isLogged() && !Security::isGuest() )17		{18			HeaderRedirect("menu");19			return false;20		}21 22		//	Not logged in23		// 	redirect to Login24		//	Current URL is already saved  in session25		redirectToLogin();26		return false;27	}28 29	public static function processAdminPageSecurity( $ajaxMode = false )30	{31		Security::processLogoutRequest();32 33		if( !isLogged() || Security::isGuest() )34		{35			Security::tryRelogin();36		}37 38		if( Security::isAdmin() )39			return true;40 41		if( $ajaxMode )42		{43			Security::sendPermissionError();44			return false;45		}46 47		// The user is logged in but lacks necessary permissions48		// redirect to Menu.49		if( isLogged() && !Security::isGuest() )50		{51			HeaderRedirect("menu");52			return false;53		}54 55		//	Not logged in56		// 	redirect to Login57		//	Save current URL in session58		Security::saveRedirectURL();59		redirectToLogin();60		return false;61	}62 63	public static function saveRedirectURL()64	{65		$url = $_SERVER["SCRIPT_NAME"];66		$query = "";67 68		//	don't remember dashboard elements69		if( postvalue("dashelement") )70			return;71 72		foreach( $_GET as $key=>$value )73		{74			if( $key == "a" && $value == "logout" )75				continue;76			if( $query != "" )77				$query.="&";78 79			if( is_array($value) )80			{81				$query .= rawurlencode($key."[]")."=";82				$query .= implode( rawurlencode($key."[]")."=", $value );83			}84			else85			{86				$query .= rawurlencode($key);87				if( strlen($value) )88					$query .= "=" . rawurlencode($value);89			}90		}91		if( $query != "" )92			$url .= "?" . $query;93		$_SESSION["MyURL"] = $url;94	}95 96	public static function checkPagePermissions( $table, $permission )97	{98		//	log out if received ?a=logout request99		Security::processLogoutRequest();100		// save current URL101		Security::saveRedirectURL();102 103		$ret = Security::checkUserPermissions( $table, $permission );104		//	remember if current user has permissions on the page saved in $_SESSION[MyURL]105		$_SESSION["MyUrlAccess"] = $ret;106		return $ret;107	}108 109	public static function createLoginPageObject()110	{111		include_once(getabspath('classes/loginpage.php'));112		include_once(getabspath('include/xtempl.php'));113		$loginXt = new Xtempl();114 115		$loginParams = array("pageType" => PAGE_LOGIN);116		$loginParams['id'] = -1;117		$loginParams['xt'] = &$loginXt;118		$loginParams["tName"]= GLOBAL_PAGES;119		$loginParams['needSearchClauseObj'] = false;120		$loginParams["providerCode"] = Security::currentProviderCode();121		$loginPageObject = new LoginPage($loginParams);122		$loginPageObject->init();123		return $loginPageObject;124	}125 126	/**127	 * Try to login automatically using saved login data128	 */129	static function tryRelogin()130	{131		//	dont' do anything if already logged in132		if( isLogged() && !Security::isGuest() ) {133			return;134		}135 136		//	don't try if we have just logged out137		if( postvalue("a") == "logout" )138			return;139 140		//	don't relogin with POST requests141		if( isPostRequest() )142			return;143 144		//	don't relogin if prohibited145		if( !Security::allowAutoLogin() ) {146			return;147		}148 149		$loginPageObject = null;150 151		//	try login automatically with AD152		if( Security::tryLoginAutoAd( true ) ) {153			return true;154		}155 156		//	try to relogin with username & password from cookies first157		$loginToken = postvalue("token");158		if( !$loginToken ) {159			$loginToken = $_COOKIE["token"];160		}161		if( $loginToken ) {162			$tokenPayload = Security::verifyKeepLoggedToken( $loginToken );163			if( $tokenPayload ) {164				Security::loginAs( $tokenPayload["username"], true );165				return true;166			}167			//	clear cookie if weren't able to login168			Security::setKeepLoggedCookie( false );169		}170 171		//	try security plugins172		$securityPlugins = Security::GetPlugins();173		foreach( $securityPlugins as $sp )174		{175			$token = $sp->savedToken();176			if( $token ) {177				if( !$loginPageObject )178					$loginPageObject = Security::createLoginPageObject();179 180				if( $loginPageObject->LoginWithSP( $sp, $token, false ) )181					return true;182			}183		}184 185		return false;186	}187 188	static function checkUserPermissions($table, $permission)189	{190		//	user is logged in191		if( !isLogged() || Security::isGuest() )192		{193			Security::tryRelogin();194		}195		//	admin area security196		if( $table == ADMIN_USERS )197			return Security::isAdmin();198 199		return CheckTablePermissions($table, $permission);200	}201 202	/**203	 * Returns true if logged out204	 * @return Boolean205	 */206	static function processLogoutRequest()207	{208		//	no need to logout209		if( postvalue("a") != "logout" )210			return false;211 212		if( Security::userSessionLevel() === LOGGED_NONE || Security::isGuest() )213			return false;214 215		//	logout and redirect (refresh current page)216		$loginPageObject = Security::createLoginPageObject();217		$loginPageObject->Logout();218		//	login as guest219		Security::doGuestLogin();220 221		global $logoutPerformed;222		if( postvalue("reason") != "expired" )223			$logoutPerformed = true;224 225		return true;226	}227 228	/**229	 * @param String message (optional)230	 */231	public static function sendPermissionError( $message = '' )232	{233		echo printJSON(array("success" => false, "message" => "You don't have permissions to access this table" . " " .$message ) );234		exit();235	}236 237	public static function redirectToList( $table )238	{239		$settings = new ProjectSettings( $table );240		if( $settings->hasListPage() )241		{242			HeaderRedirect($settings->getShortTableName(), "list", "a=return");243			exit();244		}245		//	no List page246		HeaderRedirect("menu");247		exit();248	}249 250	public static function clearSecuritySession()251	{252		session_unset();253		Security::setKeepLoggedCookie( false );254 255 256		// these lines are important257		// DO NOT REMOVE THEM!258		unset( $_COOKIE["username"] );259		unset( $_COOKIE["password"] );260		unset( $_COOKIE["token"] );261		unset( $_COOKIE["runnerSession"] );262 263		setProjectCookie("runnerSession", "", time() - 1, true );264		//	the rest of the cookies are removed within the setKeepLoggedCookie call265 266 267		storageDelete( "UserID" );268		storageDelete( "UserName" );269		storageDelete( "AccessLevel" );270		storageDelete( "UserRights" );271		storageDelete( "LastReadRights" );272		storageDelete( 'GroupID' );273		storageDelete( "OwnerID" );274		storageDelete( "securityOverrides" );275		storageDelete( "runnerSession" );276		storageDelete( "AutomaticLogin" );277		storageDelete( "logout_token_hint" );278		storageDelete( "rawUserData" );279 280		$toClear = array();281		foreach( $_SESSION as $k => $v )282		{283			if( substr($k, -8) == "_OwnerID" )284				$toClear[] = $k;285			if( substr($k, 0, 11) == "oauthToken_")286				$toClear[] = $k;287		}288		foreach( $toClear as $k )289		{290			storageDelete( $k );291		}292	}293 294	public static function doGuestLogin()295	{296		if( !Security::guestLoginAvailable() ) {297			return;298		}299		Security::createUserSession( null, "" );300	}301 302	/**303	 * Security API calls304	 */305 306	/**307	 *	Return current user's group when Static Permissions are used.308	 *	When Dynamic permissions are used, returns any group name the user belongs to309	 *	@return String310	 */311	public static function getUserGroup()312	{313		$userGroups = Security::getUserGroups();314		foreach( $userGroups as $g => $v )315		{316			return $g;317		}318		return "";319	}320 321	/**322	 *	Return array of the group IDs the user belongs to. Group Ids are the keys of the array:323	 *	$groups[ <group1> ] = true;324	 *	$groups[ <group2> ] = true;325	 *	Admin group ID is -1326	 *	When Static permissions are used, the array has only one element.327	 *	Returns empty array when the user is Guest or not logged in.328	 *	@return Array329	 */330	public static function getUserGroupIds()331	{332		global $globalSettings;333		if( !Security::userGroupsAvailable() )334			return array();335 336		if( !Security::dynamicPermissions() ) {337			//	static permissions338			if( storageGet( "GroupID" ) )339				return array( storageGet( "GroupID" ) => true );340			return array();341		}342 343		$groups = array();344		$userRights = &Security::dynamicUserRights();345		$arrgroups = &$userRights[ ".Groups" ];346		foreach( $arrgroups as $g ) {347			$groups[ $g ] = true;348		}349		return $groups;350	}351 352	/**353	 *	Return array of the group names the user belongs to. Group names are the keys of the array:354	 *	$groups[ <group1> ] = true;355	 *	$groups[ <group2> ] = true;356	 *	When Static permissions option is used, the array has only one element.357	 *	$groups[ <groupId> ] = true;358	 *	Returns empty array when the user is Guest or not logged in or doesn't belong to any group.359	 *	@return Array360	 */361	public static function getUserGroups()362	{363		global $globalSettings;364		if( !Security::userGroupsAvailable() )365			return array();366		if( !Security::dynamicPermissions() )367			return Security::getUserGroupIds();368 369		//	todo AD groups370 371		// database-based dynamic permissions372		$groupIds = Security::getUserGroupIds();373 374		$groupNames = array();375 376		global $cman;377		$grConnection = $cman->getForUserGroups();378 379		$sql = "select ". $grConnection->addFieldWrappers( "Label" )380			." from ". $grConnection->addTableWrappers( "Chat2uggroups" ) . " WHERE " . $grConnection->addFieldWrappers( "GroupID" )381			." in ( " . implode( ",", array_keys( $groupIds ) ) . ")";382 383		$qResult = $grConnection->query( $sql );384		while( $data = $qResult->fetchNumeric() )385		{386			$groupNames[ $data[0] ] = true;387		}388 389		if( $groupIds[ -1 ] )390			$groupNames["<Admin>"] = true;391 392		return $groupNames;393	}394 395	/**396	 *	Return current user's name, the same he entered when logging in.397	 *	@return String398	 */399	public static function getUserName()400	{401		$ret = storageGet( "UserID" );402		if( is_null($ret) ) {403			return "";404		}405		return $ret;406	}407 408	/**409	 *  Current User ID. For all providers except AD it matches the getUserName result.410	*  For AD it is <provider code><username>411	 *	@return String412	 */413	public static function getUserId()414	{415		$userId = Security::userSessionLevel() == LOGGED_FULL416			? storageGet( "UserID" )417			: Security::provisionalUsername();418		$provider =& Security::currentProvider();419		if( $provider[ "type" ] != stAD )420			return $userId;421		return $provider[ "code" ] . $userId;422	}423 424	/**425	 *	Return current user's display name, the one to be displayed on the pages.426	 *	@return String427	 */428	public static function getDisplayName()429	{430		return storageGet( "UserName" );431	}432	/**433	 *	Change the current user's display name, the one to be displayed on the pages.434	 *	@param String $str - new name, HTML formatting is allowed435	 */436	public static function setDisplayName( $str )437	{438		storageSet( "UserName",  $str );439	}440 441	/**442	 * 	Synchronize user's display name cache state with db value443	 */444	public static function refreshDisplayName() {445		$userData = Security::getUserData( Security::getUserName() );446		$fullnameField = Security::fullnameField();447		if( !$fullnameField ) {448			return;449		}450		$fullName = $userData[ $fullnameField ];451		Security::setDisplayName( runner_htmlspecialchars($fullName) );452	}453 454	/**455	 *	Checks if the current user is Guest or not.456	 *	@return Boolean457	 */458	public static function isGuest()459	{460		if( Security::getUserName() == "Guest" && storageGet( "AccessLevel" ) == ACCESS_LEVEL_GUEST )461			return true;462		return false;463	}464 465	/**466	 *	Checks if the current user is Dynamic permissions admin or not.467	 *	@return Boolean468	 */469	public static function isAdmin()470	{471		if( !isLogged() )472			return false;473		if( !Security::dynamicPermissions() ) {474			return false;475		}476		$userRights = &Security::dynamicUserRights();477		return $userRights[ ".IsAdmin" ];478	}479 480	/**481	 *	Checks if the current user is logged in.482	 *	@return Boolean483	 */484	public static function isLoggedIn()485	{486		return ( IsLogged() && !Security::isGuest() );487	}488 489	/**490	 *	Logs in under specified username491	 *	@param String $username492	 *	@param Boolean $fireEvents - call After Successful Login event or not493	 *	@returns Boolean - true if login was successful494	 */495	public static function loginAs( $username, $fireEvents = true, $displayName = "", $userData = array() )496	{497		$provider = Security::defaultProvider();498		if( !$provider ) {499			return;500		}501		if( Security::hardcodedLogin() ) {502			Security::createUserSession( $provider, $username, "" );503		} else if( $provider["type"] == stDB ) {504			if( !$userData )505				$userData = Security::fetchUserData( $username, "", true );506			if( !$userData ) {507				//	user deleted?508				return false;509			}510			Security::createUserSession(  $provider, $userData[ Security::usernameField() ], $userData[ Security::fullnameField() ], $userData );511		} else if( $provider["type"] == stAD ) {512			$plugin = Security::getAuthPlugin( $provider["code"] );513			$plugin->loginAsUser( $username );514		}515		if( $fireEvents ) {516			Security::auditLoginSuccess();517 518			//	fire after successfulLogin event519			global $globalEvents;520			if( $globalEvents->exists("AfterSuccessfulLogin") )521			{522				$globalEvents->AfterSuccessfulLogin( $username, "", $userData, null );523			}524		}525		return true;526	}527 528	/**529	 * @param String username530	 * @param String password531	 * @param Boolean fireEvents (optional)  Run after unsuccessful event if login/password are incorrect.532	 * @return Boolean533	 */534	public static function checkUsernamePassword( $username, $password, $fireEvents = false )535	{536		$data = Security::fetchUserData( $username, $password, false );537		if( $data ) {538			return true;539		}540		if( $fireEvents )541		{542			global $globalEvents;543			$message = "";544			if( $globalEvents->exists("AfterUnsuccessfulLogin") )545				$globalEvents->AfterUnsuccessfulLogin( $username, $password, $message, null, null );546		}547		return false;548	}549 550	/**551	 * Check username/password and login if successful552	 * @param String username553	 * @param String password554	 * @param Boolean fireEvents (optional)  Run after unsuccessful event if login/password are incorrect.555	 * @return Boolean556	 */557	public static function login( $username, $password, $skipPasswordCheck = false, $fireEvents = true )558	{559 560		if( Security::hardcodedLogin() ) {561			if( $skipPasswordCheck || Security::verifyHardcodedLogin( $username, $password ) ) {562				return Security::loginAs( Security::hardcodedUsername(), $fireEvents );563			}564		} else {565			$userData = Security::fetchUserData( $username, $password, $skipPasswordCheck );566			if( $userData ) {567				return Security::loginAs( $username, $fireEvents, "", $userData );568			}569		} /* else if( $lMethod === LOGIN_AD ) {570			$loginPageObject = Security::createLoginPageObject();571			return $loginPageObject->LogIn($username, $password, $skipPasswordCheck, $fireEvents );572		} */573		if( $fireEvents ) {574			//	call unsuccessful login event575			Security::auditLoginFail( $username );576			global $globalEvents;577			if( $globalEvents->exists("AfterUnsuccessfulLogin") )578			{579				$message = "";580				$globalEvents->AfterUnsuccessfulLogin( $username, $password, $message, null, array() );581			}582		}583		return false;584	}585 586 587	/**588	 * @param String username589	 * @param String password (optional)590	 * @return Array591	 */592	public static function getUserData( $username, $password = "" )593	{594		return Security::fetchUserData( $username, $password, $password === "" );595	}596 597	/**598	 * This function must return data in case of provisional sessions as well!599	 * @return Array600	 */601	public static function & currentUserData( )602	{603		return storageGet("UserData");604	}605 606 607 608	/**609	 *	Logs the current user out610	 */611	public static function logout()612	{613		$loginPageObject = Security::createLoginPageObject();614		$loginPageObject->Logout();615	}616 617	/**618	 *	Returns table permissions array the current user.619	 *	Returns array where keys are specific permission letters:620	 * 	A - add,621	 *  D - delete,622	 *  E - edit,623	 *  S - search/list,624	 *  P - print/export,625	 *  I - import,626	 *	M - admin permission. When advanced permissions are in effect ( users can see/edit their own records only ), this permissions grants access to all records.627	 *628	 *  Sample:629	 *		$rights = Security::getPermissions( $table );630	 *		if( $rights["A"] )631	 *		echo "add permission available";632	 *633	 *	@param String $table - table name634	 *  @returns Array635	 */636	public static function getPermissions( $table )637	{638		$table = findTable( $table );639		if( $table == "" )640			return array();641 642		return Security::permMask2Array( GetUserPermissions( $table ) );643	}644 645	/**646	 *	Set table permissions for the current user.647	 *	Permissions should be passed in the form of array where keys are specific permission letters:648	 * 	A - add,649	 *  D - delete,650	 *  E - edit,651	 *  S - search/list,652	 *  P - print/export,653	 *  I - import,654	 *	M - admin permission. When advanced permissions are in effect ( users can see/edit their own records only ), this permissions grants access to all records.655	 *656	 *  Sample:657	 *		$rights = Security::getPermissions( $table );658	 *		$rights["A"] = true;659	 *		$rights["D"] = false;660	 *		Security::setPermissions( $table, $rights );661	 *662	 *  Permissions need to be set only once per user session, i.e. in the 'After Successful Login' event.663	 *664	 *	@param String $table - table name665	 *	@param Array $rights666	 *  @returns nothing667	 */668 669	public static function setPermissions( $table, $rights )670	{671		$table = findTable( $table );672		if( $table == "" )673			return;674 675		if( !is_array( $rights ) ) {676			$rights = Security::permMask2Array( $rights );677		}678	679		//	reset restricted pages when previously disabled permssion is enabled680		$oldPerm = Security::permMask2Array( GetUserPermissions( $table ) );681		foreach( $rights as $r => $v ) {682			if( $v && !$oldPerm[ $r ] ) {683				Security::clearRestrictedPages( $table, $r );684			}685		}686 687		$overrides =& Security::createSecurityOverrides( $table );688		$overrides[ "mask" ] = Security::permArray2Mask( $rights );689	}690 691	/**692	 * Clear restricted pages for all page types controlled by $perm permission693	 */694	protected static function clearRestrictedPages( $table, $perm ) {695		$pSet = new ProjectSettings( $table );696		$pages = $pSet->getOriginalPages();697		$clearPageTypes = array();698		foreach( $pages as $page => $pageType ) {699			if( $perm != Security::pageType2permission( $pageType ) ) {700				continue;701			}702			$clearPageTypes[ $pageType ] = true;703		}704		foreach( $clearPageTypes as $pageType => $d ) {705			Security::_setRestrictedPages( $table, $pageType, array(), $pSet );706		}707 708	}709 710	private static function _setRestrictedPages( $table, $pageType, $pages, $pSet ) {711 712		$currentPages = Security::getRestrictedPages( $table, $pSet );713		$newPages = array();714		foreach( $currentPages as $p ) {715			if( $pSet->getOriginalPageType( $p ) !== $pageType ) {716				$newPages[ $p ] = true;717			}718		}719 720		if( $pages ) {721			foreach( $pages as $p ) {722				$newPages[ $p ] = true;723			}724		}725 726		$overrides =& Security::createSecurityOverrides( $table );727		$overrides[ "pages" ] = $newPages;728		$pSet->resetPages();729	}730 731	public static function setRestrictedPages( $table, $type, $pages )732	{733		if( $table !== GLOBAL_PAGES ) {734			$table = findTable( $table );735			if( $table == "" )736				return;737		}738		if( !is_array( $pages ) ) {739			$pages = array( $pages );740		}741		Security::_setRestrictedPages( $table, $pageType, $pages, new ProjectSettings( $table ) );742	}743 744	public static function setAllowedPages( $table, $type, $allowedPages )745	{746		if( $table !== GLOBAL_PAGES ) {747			$table = findTable( $table );748			if( $table == "" )749				return;750		}751		if( !is_array( $allowedPages ) ) {752			$allowedPages = array( $allowedPages );753		}754 755		$pSet = new ProjectSettings( $table );756		$allPages = $pSet->getOriginalPagesByType( $type );757		$pages = array();758		foreach( $allPages as $p ) {759			if( !in_array( $p, $allowedPages ) )760				$pages[] = $p;761		}762 763		Security::_setRestrictedPages( $table, $pageType, $pages, $pSet );764	}765 766	private static function & createSecurityOverrides( $table ) {767		if( !isset( $_SESSION[ "securityOverrides" ] ) )768			$_SESSION[ "securityOverrides" ] = array();769		if( !isset( $_SESSION[ "securityOverrides" ][ $table ] ) )770			$_SESSION[ "securityOverrides" ][ $table ] = array();771		return $_SESSION[ "securityOverrides" ][ $table ];772	}773 774	private static function permMask2Array( $str )775	{776		$ret = array();777		for( $i = 0; $i < strlen($str); ++$i )778		{779			$c = substr( $str, $i, 1 );780			if( $c == "A" || $c == "D" || $c == "E" || $c == "S" || $c == "P" || $c == "I" || $c == "M" )781				$ret[ $c ] = true;782		}783		return $ret;784	}785 786	private static function permArray2Mask( $rights )787	{788		$str = "";789		if( !is_array( $rights ) )790		{791			if( strlen( $rights ) )792				$rights = Security::permMask2Array( $rights );793			else794				return "";795		}796		foreach( $rights as $c => $v )797			if( $v && ( $c == "A" || $c == "D" || $c == "E" || $c == "S" || $c == "P" || $c == "I" || $c == "M" ) )798				$str .= $c;799		return $str;800	}801 802 803	/**804	 *	Returns current user's OwnerID - the value used to identify records ownership in the specific table.805	 *806	 *	@param String $table - table name807	 *  @returns String808	 */809	public static function getOwnerId( $table )810	{811		$table = findTable( $table );812		if( $table == "" )813			return;814 815		return storageGet( "_" . $table . "_OwnerID" );816	}817 818	/**819	 *	Change current user's OwnerID - the value used to identify records ownership in the specific table.820	 *821	 *	@param String $table - table name822	 *  @param String $ownerid823	 */824	public static function setOwnerId( $table, $ownerid )825	{826		$table = findTable( $table );827		if( $table == "" )828			return;829 830		storageSet( "_" . $table . "_OwnerID" , $ownerid );831	}832 833	public static function hasLogin() {834 835		return getSecurityOption( "enabled" );836	}837 838	public static function loginMethod() {839		return SECURITY_TABLE;840	}841 842	public static function dynamicPermissions() {843		//	the rest of checks are made in the TS code844		return getSecurityOption( "dynamicPermissions" );845	}846 847	/**848	 * Returns true if permissions are defined in the project.849	 * When false, no permissions system is present in the project. Everyone sees everything.850	 * @return Boolean851	 */852	public static function permissionsAvailable() {853		if( !Security::hasUsers() )854			return false;855		return Security::dynamicPermissions() || GetGlobalData("userGroupCount");856	}857 858	/**859	 * Returns true if there are users in the project.860	 * When false, there may be single hardcoded login in the project, but no different users861	 * @return Boolean862	 */863	public static function hasUsers() {864		return getSecurityOption( "enabled" ) && !getSecurityOption( "hardcodedLogin" );865	}866 867 868	/**869	 * 	$permission - one of A,D,E,S,P,I literals870	 *  $table that the permissions are requested on871	 *  $ownerId - ownerId of the record the permissions is requested on872	 */873	public static function userCan( $permission, $table, $ownerId = null )874	{875		if( !Security::hasLogin() ) {876			return true;877		}878 879		$strPerm = GetUserPermissions( $table );880 881		// no permissions882		if( strpos( $strPerm, $permission ) === false )883			return false;884 885		//	record ownerId check not requested or user has admin permissions886		if( $ownerId === null || strpos($strPerm, "M") !== false )887			return true;888 889		$pSet = new ProjectSettings($table);890		$advSecType = $pSet->getAdvancedSecurityType();891		if( $advSecType == ADVSECURITY_ALL || $advSecType == ADVSECURITY_NONE /*????*/  )892			return true;893 894		if( $advSecType == ADVSECURITY_EDIT_OWN && $permission != 'D' && $permission != 'E' ) {895			return true;896		}897 898		$currentOwnerId = (string)storageGet( "_".$table."_OwnerID" );899		if( Security::caseInsensitiveUsername() ) {900			$ownerId = strtoupper( $ownerId );901			$currentOwnerId = strtoupper( $currentOwnerId );902		}903 904		return ( "".$ownerId ) === ( "".$currentOwnerId );905	}906 907	/**908	 * 	User has permissions on fields specified on the Register page and on the fields from pages he has access to909	 *  pageName can be substituted by another page910	 *911	 *  @param String table912	 *  @param String field913	 *  @param String pageType914	 *  @param String pageName915	 *  @param Boolean edit. Either we are asking to show field916	 */917	public static function userHasFieldPermissions( $table, $field, $pageType, $pageName, $edit ) {918		$pageTable = $table;919		if( $table === Security::loginTable() && ( $pageType === "register" || $pageType === "userinfo" ) ) {920			$pageTable = GLOBAL_PAGES;921		}922		$pSet = new ProjectSettings( $table, $pageType, $pageName, $pageTable );923		$pageType = $pSet->getPageType();924 925		$permission = Security::pageType2permission( $pageType );926		if( $pageTable != GLOBAL_PAGES && !Security::userCan( $permission, $table ) ) {927			return false;928		}929 930 931		//	search panel fields932		if( $edit && !pageTypeInputsData( $pageType ) ) {933			if( $pSet->appearOnSearchPanel( $field ) ) {934				return true;935			}936			if( $pageType == "list") {937				return $pSet->hasInlineEdit() && $pSet->appearOnInlineEdit( $field )938				|| $pSet->hasInlineAdd() && $pSet->appearOnInlineAdd( $field );939			}940		}941		if( !$edit && !pageTypeShowsData( $pageType ) )942			return false;943		return $pSet->appearOnPage( $field );944	}945 946	public static function getRestrictedPages( $table, $pSet )947	{948		global $globalEvents;949		950		if( $globalEvents->exists("GetTablePermissions", $table) ) {951			//	ignore page-level permissions when GetTablePermissions event is used952			return array();953		}954 955		if( is_array( $_SESSION["securityOverrides"] ) )956		{957			if( isset( $_SESSION["securityOverrides"][ $table ] ) ) {958				if( isset( $_SESSION["securityOverrides"][ $table ][ "pages" ] ) ) {959					return $_SESSION["securityOverrides"][ $table ][ "pages" ];960				}961			}962		}963		if( !Security::dynamicPermissions() ) {964			return Security::_staticRestrictedPages( $table );965		}966 967		$userRights = &Security::dynamicUserRights();968		$groups = &$userRights[ ".Groups" ];969 970		$allPages = $pSet->getOriginalPages();971		$ret = array();972		if( $userRights[$table] ) {973			$groupRights = $userRights[$table]["groupRights"];974		}975		if( !$groupRights ) {976			$groupRights = array();977		}978 979		foreach( $allPages as $p => $pageType ) {980			$pagePerm = Security::pageType2permission( $pageType );981			if( !Security::specialPermissionsTable( $table ) ) {982				//	page must be available in one of the groups983				$allowed = false;984				foreach( $groupRights as $gr ) {985					if( strpos( $gr["mask"], $pagePerm ) !== false && !$gr["pages"][ $p ] ) {986						$allowed = true;987						break;988					}989				}990			} else {991				//	admin and common pages. Only look for restrictions992				//	Restricted pages must be restricted in all groups the user belongs to993				$restricted = true;994				foreach( $groups as $g ) {995					if( !$groupRights[$g] ) {996						$restricted = false;997						break;998					}999					if( !$groupRights[$g]["pages"][ $p ] ) {1000						$restricted = false;1001						break;1002					}1003				}1004				$allowed = !$restricted;1005			}1006			if( !$allowed ) {1007				$ret[ $p ] = true;1008			}1009		}1010		return $ret;1011	}1012 1013	public static function pageType2permission( $pageType ) {1014		if( $pageType == "add" )1015			return "A";1016		else if( $pageType == "edit" )1017			return "E";1018		else if( $pageType == "print" || $pageType == "export" || $pageType == "rprint" || $pageType == "masterprint" || $pageType == "masterrprint" )1019			return "P";1020		else if( $pageType == "import" )1021			return "I";1022		return "S";1023	}1024 1025	public static function _staticRestrictedPages( $table ) {1026		$group = Security::getUserGroup();1027		if( $group == "admin" )	{1028			return array();1029		}1030		//	default permissions1031		return array();1032	}1033 1034	public static function getAuthPlugin( $code ) {1035		require_once( getabspath('classes/security/securityplugin.php') );1036		$provider = Security::findProvider( $code );1037		if( !$provider ) {1038			return null;1039		}1040		return Security::PluginFactory( $provider );1041	}1042 1043	/**1044	 * @param object $params1045	 * @param integer $providerType stFACEBOOK, stGOOGLE, ...1046	 * @return SecurityPlugin|null1047	 */1048	protected static function PluginFactory( $providerParams ) {1049		require_once( getabspath('classes/security/securityplugin.php') );1050 1051		$providerType = $providerParams[ "type" ];1052 1053		if( $providerType == stFACEBOOK ) {1054			require_once( getabspath( 'classes/security/fb.php' ) );1055			return new SecurityPluginFB( $providerParams );1056		}1057 1058		if( $providerType == stGOOGLE ) {1059			require_once( getabspath( 'classes/security/google.php' ) );1060			return new SecurityPluginGoogle( $providerParams );1061		}1062 1063		if( $providerType == stOPENID ) {1064			require_once( getabspath( 'classes/security/openid.php' ) );1065			return new SecurityPluginOpenId( $providerParams );1066		}1067 1068		if( $providerType == stSAML ) {1069			require_once( getabspath( 'classes/security/samlPlugin.php' ) );1070			return new SecurityPluginSaml( $providerParams );1071		}1072 1073		if( $providerType == stOKTA ) {1074			require_once( getabspath( 'classes/security/okta.php' ) );1075			return new SecurityPluginOkta( $providerParams );1076		}1077 1078		if( $providerType == stAZURE ) {1079			require_once( getabspath( 'classes/security/azure.php' ) );1080			return new SecurityPluginAzure( $providerParams );1081		}1082 1083		if( $providerType == stAD ) {1084			require_once( getabspath( 'classes/security/ad.php' ) );1085			return new SecurityPluginAd( $providerParams );1086		}1087 1088		return null;1089	}1090 1091 1092	/**1093	 * @return Array( "providerKey" => SecurityPlugin )1094	 */1095	public static function GetPlugins() {1096		$plugins = array();1097		// provider type => provider code1098		$providersCfg = array(1099			stFACEBOOK => "fb",1100			stGOOGLE => "go"1101		);1102 1103		foreach( $providersCfg as $type => $code ) {1104			$providers = Security::providersByType( $type );1105			if( $plugins[ $code ] == null && count( $providers ) != 0 ) {1106				$plugins[ $code ] = Security::PluginFactory( $providers[0] );1107			}1108		}1109 1110		return $plugins;1111	}1112 1113	/**1114	 * DEPRECATED1115	 * ???1116	 */1117	public static function getLoginTable() {1118		return Security::loginTable();1119	}1120 1121	/**1122	 * Test whether the user has permissions to see the page1123	 */1124	public static function userCanSeePage( $table, $page ) {1125		$pSet = new ProjectSettings( $table, "", $page );1126		if( $pSet->pageName() != $page )1127			return false;1128		if( $table == GLOBAL_PAGES )1129			return true;1130		$permission = Security::pageType2permission( $pSet->getPageType() );1131		if( !$permission ) {1132			//	page doesn't require permissions1133			return true;1134		}1135		$strPerm = GetUserPermissions( $table );1136		return strpos( $strPerm, $permission ) !== false;1137	}1138 1139	/**1140	 * @param String - one of the permission letters: 'ADESPIM'1141	 * @param ProjectSettings1142	 * @param Boolean - don't check if the user has permissions on the table. Check record-level permissions only.1143	 * 					This flag is for lookup wizards1144	 * @return DsCondition or null if no condition needed1145	 */1146	public static function SelectCondition( $strRequestedPremission, $pSet, $skipTablePermissions = false )1147	{1148		//	not a project table1149		if( !$pSet ) {1150			return null;1151		}1152 1153		if( !Security::hasUsers() ) {1154			return null;1155		}1156 1157		$strPerm = GetUserPermissions( $pSet->table() );1158		if( !$skipTablePermissions && strpos( $strPerm, $strRequestedPremission ) === false ) {1159			return DataCondition::_False();1160		}1161 1162		$ownerid = storageGet( "_" . $pSet->table() . "_OwnerID" );1163 1164 1165		$tableAdvSecurity = $pSet->getAdvancedSecurityType();1166		if( strpos($strPerm, "M") !== false ) {1167			return null;1168		}1169 1170		if ( $tableAdvSecurity == ADVSECURITY_VIEW_OWN1171				||  $tableAdvSecurity == ADVSECURITY_EDIT_OWN1172					&& ( $strRequestedPremission == "E" || $strRequestedPremission == "D") ) {1173			return DataCondition::FieldEquals( $pSet->getTableOwnerID(), $ownerid );1174		}1175 1176		return null;1177	}1178 1179	/**1180	 * Get DataSource for ug_members table1181	 * @return DataSource1182	 */1183	public static function getUgMembersDatasource() {1184		if( !Security::dynamicPermissions() ) {1185			return null;1186		}1187		global $cman;1188		return getDbTableDataSource( "Chat2ugmembers", $cman->getUserGroupsConnId() );1189	}1190 1191	/**1192	 * Get DataSource for ug_groups table1193	 * @return DataSource1194	 */1195	public static function getUgGroupsDatasource() {1196		if( !Security::dynamicPermissions() ) {1197			return null;1198		}1199		global $cman;1200		return getDbTableDataSource( "Chat2uggroups", $cman->getUserGroupsConnId() );

Showing the first 1,200 of 2999 lines. Download the file for the rest.