idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
7,500
|
public function scopeAgentUserTickets ( $ query , $ id ) { return $ query -> where ( function ( $ subquery ) use ( $ id ) { $ subquery -> where ( 'agent_id' , $ id ) -> orWhere ( 'user_id' , $ id ) ; } ) ; }
|
Get all agent tickets .
|
7,501
|
public function autoSelectAgent ( ) { $ cat_id = $ this -> category_id ; $ agents = Category :: find ( $ cat_id ) -> agents ( ) -> with ( [ 'agentOpenTickets' => function ( $ query ) { $ query -> addSelect ( [ 'id' , 'agent_id' ] ) ; } ] ) -> get ( ) ; $ count = 0 ; $ lowest_tickets = 1000000 ; $ first_admin = Agent :: admins ( ) -> first ( ) ; $ selected_agent_id = $ first_admin -> id ; foreach ( $ agents as $ agent ) { if ( $ count == 0 ) { $ lowest_tickets = $ agent -> agentOpenTickets -> count ( ) ; $ selected_agent_id = $ agent -> id ; } else { $ tickets_count = $ agent -> agentOpenTickets -> count ( ) ; if ( $ tickets_count < $ lowest_tickets ) { $ lowest_tickets = $ tickets_count ; $ selected_agent_id = $ agent -> id ; } } $ count ++ ; } $ this -> agent_id = $ selected_agent_id ; return $ this ; }
|
Sets the agent with the lowest tickets assigned in specific category .
|
7,502
|
public function addAdministrators ( $ user_ids ) { $ users = Agent :: find ( $ user_ids ) ; foreach ( $ users as $ user ) { $ user -> ticketit_admin = true ; $ user -> save ( ) ; $ users_list [ ] = $ user -> name ; } return $ users_list ; }
|
Assign users as administrators .
|
7,503
|
public function removeAdministrator ( $ id ) { $ administrator = Agent :: find ( $ id ) ; $ administrator -> ticketit_admin = false ; $ administrator -> save ( ) ; if ( version_compare ( app ( ) -> version ( ) , '5.2.0' , '>=' ) ) { $ administrator_cats = $ administrator -> categories -> pluck ( 'id' ) -> toArray ( ) ; } else { $ administrator_cats = $ administrator -> categories -> lists ( 'id' ) -> toArray ( ) ; } $ administrator -> categories ( ) -> detach ( $ administrator_cats ) ; return $ administrator ; }
|
Remove user from the administrators .
|
7,504
|
public function syncAdministratorCategories ( $ id , Request $ request ) { $ form_cats = ( $ request -> input ( 'administrator_cats' ) == null ) ? [ ] : $ request -> input ( 'administrator_cats' ) ; $ administrator = Agent :: find ( $ id ) ; $ administrator -> categories ( ) -> sync ( $ form_cats ) ; }
|
Sync Administrator categories with the selected categories got from update form .
|
7,505
|
public function index ( ) { $ configurations = Configuration :: all ( ) ; $ configurations_by_sections = [ 'init' => [ ] , 'email' => [ ] , 'tickets' => [ ] , 'perms' => [ ] , 'editor' => [ ] , 'other' => [ ] ] ; $ init_section = [ 'main_route' , 'main_route_path' , 'admin_route' , 'admin_route_path' , 'master_template' , 'bootstrap_version' , 'routes' ] ; $ email_section = [ 'status_notification' , 'comment_notification' , 'queue_emails' , 'assigned_notification' , 'email.template' , 'email.header' , 'email.signoff' , 'email.signature' , 'email.dashboard' , 'email.google_plus_link' , 'email.facebook_link' , 'email.twitter_link' , 'email.footer' , 'email.footer_link' , 'email.color_body_bg' , 'email.color_header_bg' , 'email.color_content_bg' , 'email.color_footer_bg' , 'email.color_button_bg' , ] ; $ tickets_section = [ 'default_status_id' , 'default_close_status_id' , 'default_reopen_status_id' , 'paginate_items' ] ; $ perms_section = [ 'agent_restrict' , 'close_ticket_perm' , 'reopen_ticket_perm' ] ; $ editor_section = [ 'editor_enabled' , 'include_font_awesome' , 'editor_html_highlighter' , 'codemirror_theme' , 'summernote_locale' , 'summernote_options_json_file' , 'purifier_config' , ] ; foreach ( $ configurations as $ config_item ) { $ config_item -> value = $ config_item -> getShortContent ( 25 , 'value' ) ; $ config_item -> default = $ config_item -> getShortContent ( 25 , 'default' ) ; if ( in_array ( $ config_item -> slug , $ init_section ) ) { $ configurations_by_sections [ 'init' ] [ ] = $ config_item ; } elseif ( in_array ( $ config_item -> slug , $ email_section ) ) { $ configurations_by_sections [ 'email' ] [ ] = $ config_item ; } elseif ( in_array ( $ config_item -> slug , $ tickets_section ) ) { $ configurations_by_sections [ 'tickets' ] [ ] = $ config_item ; } elseif ( in_array ( $ config_item -> slug , $ perms_section ) ) { $ configurations_by_sections [ 'perms' ] [ ] = $ config_item ; } elseif ( in_array ( $ config_item -> slug , $ editor_section ) ) { $ configurations_by_sections [ 'editor' ] [ ] = $ config_item ; } else { $ configurations_by_sections [ 'other' ] [ ] = $ config_item ; } } return view ( 'ticketit::admin.configuration.index' , compact ( 'configurations' , 'configurations_by_sections' ) ) ; }
|
Display a listing of the Setting .
|
7,506
|
public function store ( Request $ request ) { $ this -> validate ( $ request , [ 'slug' => 'required' , 'default' => 'required' , 'value' => 'required' , ] ) ; $ input = $ request -> all ( ) ; $ configuration = new Configuration ( ) ; $ configuration -> create ( $ input ) ; Session :: flash ( 'configuration' , 'Setting saved successfully.' ) ; \ Cache :: forget ( 'ticketit::settings' ) ; return redirect ( ) -> action ( '\Kordy\Ticketit\Controllers\ConfigurationsController@index' ) ; }
|
Store a newly created Configuration in storage .
|
7,507
|
public function edit ( $ id ) { $ configuration = Configuration :: findOrFail ( $ id ) ; $ should_serialize = Setting :: is_serialized ( $ configuration -> value ) ; $ default_serialized = Setting :: is_serialized ( $ configuration -> default ) ; return view ( 'ticketit::admin.configuration.edit' , compact ( 'configuration' , 'should_serialize' , 'default_serialized' ) ) ; }
|
Show the form for editing the specified Configuration .
|
7,508
|
public function update ( Request $ request , $ id ) { $ configuration = Configuration :: findOrFail ( $ id ) ; $ value = $ request -> value ; if ( $ request -> serialize ) { if ( ! Auth :: attempt ( $ request -> only ( 'password' ) , false , false ) ) { return back ( ) -> withErrors ( [ trans ( 'ticketit::admin.config-edit-auth-failed' ) ] ) ; } if ( false === eval ( '$value = serialize(' . $ value . ');' ) ) { return back ( ) -> withErrors ( [ trans ( 'ticketit::admin.config-edit-eval-error' ) ] ) ; } } $ configuration -> update ( [ 'value' => $ value , 'lang' => $ request -> lang ] ) ; Session :: flash ( 'configuration' , trans ( 'ticketit::lang.configuration-name-has-been-modified' , [ 'name' => $ request -> name ] ) ) ; \ Cache :: forget ( 'ticketit::settings' ) ; \ Cache :: forget ( 'ticketit::settings.' . $ configuration -> slug ) ; return redirect ( ) -> action ( '\Kordy\Ticketit\Controllers\ConfigurationsController@index' ) ; }
|
Update the specified Configuration in storage .
|
7,509
|
public function run ( ) { $ defaults = [ ] ; $ defaults = $ this -> cleanupAndMerge ( $ this -> getDefaults ( ) , $ this -> config ) ; foreach ( $ defaults as $ slug => $ column ) { $ setting = Setting :: bySlug ( $ slug ) ; if ( $ setting -> count ( ) ) { $ setting -> first ( ) -> update ( [ 'default' => $ column , ] ) ; } else { Setting :: create ( [ 'lang' => null , 'slug' => $ slug , 'value' => $ column , 'default' => $ column , ] ) ; } } }
|
Seed the Plans table .
|
7,510
|
public function sendNotification ( $ template , $ data , $ ticket , $ notification_owner , $ subject , $ type ) { $ to = null ; if ( $ type != 'agent' ) { $ to = $ ticket -> user ; if ( $ ticket -> user -> email != $ notification_owner -> email ) { $ to = $ ticket -> user ; } if ( $ ticket -> agent -> email != $ notification_owner -> email ) { $ to = $ ticket -> agent ; } } else { $ to = $ ticket -> agent ; } if ( LaravelVersion :: lt ( '5.4' ) ) { $ mail_callback = function ( $ m ) use ( $ to , $ notification_owner , $ subject ) { $ m -> to ( $ to -> email , $ to -> name ) ; $ m -> replyTo ( $ notification_owner -> email , $ notification_owner -> name ) ; $ m -> subject ( $ subject ) ; } ; if ( Setting :: grab ( 'queue_emails' ) == 'yes' ) { Mail :: queue ( $ template , $ data , $ mail_callback ) ; } else { Mail :: send ( $ template , $ data , $ mail_callback ) ; } } elseif ( LaravelVersion :: min ( '5.4' ) ) { $ mail = new \ Kordy \ Ticketit \ Mail \ TicketitNotification ( $ template , $ data , $ notification_owner , $ subject ) ; if ( Setting :: grab ( 'queue_emails' ) == 'yes' ) { Mail :: to ( $ to ) -> queue ( $ mail ) ; } else { Mail :: to ( $ to ) -> send ( $ mail ) ; } } }
|
Send email notifications from the action owner to other involved users .
|
7,511
|
public function store ( Request $ request ) { $ this -> validate ( $ request , [ 'subject' => 'required|min:3' , 'content' => 'required|min:6' , 'priority_id' => 'required|exists:ticketit_priorities,id' , 'category_id' => 'required|exists:ticketit_categories,id' , ] ) ; $ ticket = new Ticket ( ) ; $ ticket -> subject = $ request -> subject ; $ ticket -> setPurifiedContent ( $ request -> get ( 'content' ) ) ; $ ticket -> priority_id = $ request -> priority_id ; $ ticket -> category_id = $ request -> category_id ; $ ticket -> status_id = Setting :: grab ( 'default_status_id' ) ; $ ticket -> user_id = auth ( ) -> user ( ) -> id ; $ ticket -> autoSelectAgent ( ) ; $ ticket -> save ( ) ; session ( ) -> flash ( 'status' , trans ( 'ticketit::lang.the-ticket-has-been-created' ) ) ; return redirect ( ) -> action ( '\Kordy\Ticketit\Controllers\TicketsController@index' ) ; }
|
Store a newly created ticket and auto assign an agent for it .
|
7,512
|
public function complete ( $ id ) { if ( $ this -> permToClose ( $ id ) == 'yes' ) { $ ticket = $ this -> tickets -> findOrFail ( $ id ) ; $ ticket -> completed_at = Carbon :: now ( ) ; if ( Setting :: grab ( 'default_close_status_id' ) ) { $ ticket -> status_id = Setting :: grab ( 'default_close_status_id' ) ; } $ subject = $ ticket -> subject ; $ ticket -> save ( ) ; session ( ) -> flash ( 'status' , trans ( 'ticketit::lang.the-ticket-has-been-completed' , [ 'name' => $ subject ] ) ) ; return redirect ( ) -> route ( Setting :: grab ( 'main_route' ) . '.index' ) ; } return redirect ( ) -> route ( Setting :: grab ( 'main_route' ) . '.index' ) -> with ( 'warning' , trans ( 'ticketit::lang.you-are-not-permitted-to-do-this' ) ) ; }
|
Mark ticket as complete .
|
7,513
|
public function reopen ( $ id ) { if ( $ this -> permToReopen ( $ id ) == 'yes' ) { $ ticket = $ this -> tickets -> findOrFail ( $ id ) ; $ ticket -> completed_at = null ; if ( Setting :: grab ( 'default_reopen_status_id' ) ) { $ ticket -> status_id = Setting :: grab ( 'default_reopen_status_id' ) ; } $ subject = $ ticket -> subject ; $ ticket -> save ( ) ; session ( ) -> flash ( 'status' , trans ( 'ticketit::lang.the-ticket-has-been-reopened' , [ 'name' => $ subject ] ) ) ; return redirect ( ) -> route ( Setting :: grab ( 'main_route' ) . '.index' ) ; } return redirect ( ) -> route ( Setting :: grab ( 'main_route' ) . '.index' ) -> with ( 'warning' , trans ( 'ticketit::lang.you-are-not-permitted-to-do-this' ) ) ; }
|
Reopen ticket from complete status .
|
7,514
|
public function monthlyPerfomance ( $ period = 2 ) { $ categories = Category :: all ( ) ; foreach ( $ categories as $ cat ) { $ records [ 'categories' ] [ ] = $ cat -> name ; } for ( $ m = $ period ; $ m >= 0 ; $ m -- ) { $ from = Carbon :: now ( ) ; $ from -> day = 1 ; $ from -> subMonth ( $ m ) ; $ to = Carbon :: now ( ) ; $ to -> day = 1 ; $ to -> subMonth ( $ m ) ; $ to -> endOfMonth ( ) ; $ records [ 'interval' ] [ $ from -> format ( 'F Y' ) ] = [ ] ; foreach ( $ categories as $ cat ) { $ records [ 'interval' ] [ $ from -> format ( 'F Y' ) ] [ ] = round ( $ this -> intervalPerformance ( $ from , $ to , $ cat -> id ) , 1 ) ; } } return $ records ; }
|
Calculate average closing period of days per category for number of months .
|
7,515
|
public function ticketPerformance ( $ ticket ) { if ( $ ticket -> completed_at == null ) { return false ; } $ created = new Carbon ( $ ticket -> created_at ) ; $ completed = new Carbon ( $ ticket -> completed_at ) ; $ length = $ created -> diff ( $ completed ) -> days ; return $ length ; }
|
Calculate the date length it took to solve a ticket .
|
7,516
|
public function intervalPerformance ( $ from , $ to , $ cat_id = false ) { if ( $ cat_id ) { $ tickets = Ticket :: where ( 'category_id' , $ cat_id ) -> whereBetween ( 'completed_at' , [ $ from , $ to ] ) -> get ( ) ; } else { $ tickets = Ticket :: whereBetween ( 'completed_at' , [ $ from , $ to ] ) -> get ( ) ; } if ( empty ( $ tickets -> first ( ) ) ) { return false ; } $ performance_count = 0 ; $ counter = 0 ; foreach ( $ tickets as $ ticket ) { $ performance_count += $ this -> ticketPerformance ( $ ticket ) ; $ counter ++ ; } $ performance_average = $ performance_count / $ counter ; return $ performance_average ; }
|
Calculate the average date length it took to solve tickets within date period .
|
7,517
|
public function settingsSeeder ( $ master = false ) { $ cli_path = 'config/ticketit.php' ; $ provider_path = '../config/ticketit.php' ; $ config_settings = [ ] ; $ settings_file_path = false ; if ( File :: isFile ( $ cli_path ) ) { $ settings_file_path = $ cli_path ; } elseif ( File :: isFile ( $ provider_path ) ) { $ settings_file_path = $ provider_path ; } if ( $ settings_file_path ) { $ config_settings = include $ settings_file_path ; File :: move ( $ settings_file_path , $ settings_file_path . '.backup' ) ; } $ seeder = new SettingsTableSeeder ( ) ; if ( $ master ) { $ config_settings [ 'master_template' ] = $ master ; } $ seeder -> config = $ config_settings ; $ seeder -> run ( ) ; }
|
Run the settings table seeder .
|
7,518
|
public function inactiveMigrations ( ) { $ inactiveMigrations = [ ] ; $ migration_arr = [ ] ; $ tables = $ this -> migrations_tables ; $ migrations = DB :: select ( 'select * from ' . DB :: getTablePrefix ( ) . 'migrations' ) ; foreach ( $ migrations as $ migration_parent ) { $ migration_arr [ ] = $ migration_parent -> migration ; } foreach ( $ tables as $ table ) { if ( ! in_array ( $ table , $ migration_arr ) ) { $ inactiveMigrations [ ] = $ table ; } } return $ inactiveMigrations ; }
|
Get all Ticketit Package migrations that were not migrated .
|
7,519
|
public function inactiveSettings ( ) { $ seeder = new SettingsTableSeeder ( ) ; if ( version_compare ( app ( ) -> version ( ) , '5.2.0' , '>=' ) ) { $ installed_settings = DB :: table ( 'ticketit_settings' ) -> pluck ( 'value' , 'slug' ) ; } else { $ installed_settings = DB :: table ( 'ticketit_settings' ) -> lists ( 'value' , 'slug' ) ; } if ( ! is_array ( $ installed_settings ) ) { $ installed_settings = $ installed_settings -> toArray ( ) ; } $ default_Settings = $ seeder -> getDefaults ( ) ; if ( count ( $ installed_settings ) == count ( $ default_Settings ) ) { return false ; } $ inactive_settings = array_diff_key ( $ default_Settings , $ installed_settings ) ; return $ inactive_settings ; }
|
Check if all Ticketit Package settings that were not installed to setting table .
|
7,520
|
public function getShortContent ( $ maxlength = 50 , $ attr = 'content' ) { $ content = $ this -> { $ attr } ; if ( strlen ( $ content ) > $ maxlength ) { return substr ( $ content , 0 , $ maxlength ) . '...' ; } return $ content ; }
|
Cuts the content of a comment or a ticket content if it s too long .
|
7,521
|
public function setPurifiedContent ( $ rawHtml ) { $ this -> content = Purifier :: clean ( $ rawHtml , [ 'HTML.Allowed' => '' ] ) ; $ this -> html = Purifier :: clean ( $ rawHtml , Setting :: grab ( 'purifier_config' ) ) ; return $ this ; }
|
Updates the content and html attribute of the given model .
|
7,522
|
public static function isBlacklisted ( $ email ) { $ parts = explode ( "@" , $ email ) ; $ domain = end ( $ parts ) ; foreach ( self :: allDomainSuffixes ( $ domain ) as $ domainSuffix ) { if ( in_array ( $ domainSuffix , self :: $ blacklist ) ) { return true ; } } return false ; }
|
Check if an email is blacklisted or not
|
7,523
|
public static function createFromString ( $ image_data ) { if ( empty ( $ image_data ) || $ image_data === null ) { throw new ImageResizeException ( 'image_data must not be empty' ) ; } $ resize = new self ( 'data://application/octet-stream;base64,' . base64_encode ( $ image_data ) ) ; return $ resize ; }
|
Create instance from a strng
|
7,524
|
public function output ( $ image_type = null , $ quality = null ) { $ image_type = $ image_type ? : $ this -> source_type ; header ( 'Content-Type: ' . image_type_to_mime_type ( $ image_type ) ) ; $ this -> save ( null , $ image_type , $ quality ) ; }
|
Outputs image to browser
|
7,525
|
public function resizeToBestFit ( $ max_width , $ max_height , $ allow_enlarge = false ) { if ( $ this -> getSourceWidth ( ) <= $ max_width && $ this -> getSourceHeight ( ) <= $ max_height && $ allow_enlarge === false ) { return $ this ; } $ ratio = $ this -> getSourceHeight ( ) / $ this -> getSourceWidth ( ) ; $ width = $ max_width ; $ height = $ width * $ ratio ; if ( $ height > $ max_height ) { $ height = $ max_height ; $ width = $ height / $ ratio ; } return $ this -> resize ( $ width , $ height , $ allow_enlarge ) ; }
|
Resizes image to best fit inside the given dimensions
|
7,526
|
public function resize ( $ width , $ height , $ allow_enlarge = false ) { if ( ! $ allow_enlarge ) { if ( $ width > $ this -> getSourceWidth ( ) || $ height > $ this -> getSourceHeight ( ) ) { $ width = $ this -> getSourceWidth ( ) ; $ height = $ this -> getSourceHeight ( ) ; } } $ this -> source_x = 0 ; $ this -> source_y = 0 ; $ this -> dest_w = $ width ; $ this -> dest_h = $ height ; $ this -> source_w = $ this -> getSourceWidth ( ) ; $ this -> source_h = $ this -> getSourceHeight ( ) ; return $ this ; }
|
Resizes image according to the given width and height
|
7,527
|
public function crop ( $ width , $ height , $ allow_enlarge = false , $ position = self :: CROPCENTER ) { if ( ! $ allow_enlarge ) { if ( $ width > $ this -> getSourceWidth ( ) ) { $ width = $ this -> getSourceWidth ( ) ; } if ( $ height > $ this -> getSourceHeight ( ) ) { $ height = $ this -> getSourceHeight ( ) ; } } $ ratio_source = $ this -> getSourceWidth ( ) / $ this -> getSourceHeight ( ) ; $ ratio_dest = $ width / $ height ; if ( $ ratio_dest < $ ratio_source ) { $ this -> resizeToHeight ( $ height , $ allow_enlarge ) ; $ excess_width = ( $ this -> getDestWidth ( ) - $ width ) / $ this -> getDestWidth ( ) * $ this -> getSourceWidth ( ) ; $ this -> source_w = $ this -> getSourceWidth ( ) - $ excess_width ; $ this -> source_x = $ this -> getCropPosition ( $ excess_width , $ position ) ; $ this -> dest_w = $ width ; } else { $ this -> resizeToWidth ( $ width , $ allow_enlarge ) ; $ excess_height = ( $ this -> getDestHeight ( ) - $ height ) / $ this -> getDestHeight ( ) * $ this -> getSourceHeight ( ) ; $ this -> source_h = $ this -> getSourceHeight ( ) - $ excess_height ; $ this -> source_y = $ this -> getCropPosition ( $ excess_height , $ position ) ; $ this -> dest_h = $ height ; } return $ this ; }
|
Crops image according to the given width height and crop position
|
7,528
|
public function freecrop ( $ width , $ height , $ x = false , $ y = false ) { if ( $ x === false || $ y === false ) { return $ this -> crop ( $ width , $ height ) ; } $ this -> source_x = $ x ; $ this -> source_y = $ y ; if ( $ width > $ this -> getSourceWidth ( ) - $ x ) { $ this -> source_w = $ this -> getSourceWidth ( ) - $ x ; } else { $ this -> source_w = $ width ; } if ( $ height > $ this -> getSourceHeight ( ) - $ y ) { $ this -> source_h = $ this -> getSourceHeight ( ) - $ y ; } else { $ this -> source_h = $ height ; } $ this -> dest_w = $ width ; $ this -> dest_h = $ height ; return $ this ; }
|
Crops image according to the given width height x and y
|
7,529
|
public function imageFlip ( $ image , $ mode ) { switch ( $ mode ) { case self :: IMG_FLIP_HORIZONTAL : { $ max_x = imagesx ( $ image ) - 1 ; $ half_x = $ max_x / 2 ; $ sy = imagesy ( $ image ) ; $ temp_image = imageistruecolor ( $ image ) ? imagecreatetruecolor ( 1 , $ sy ) : imagecreate ( 1 , $ sy ) ; for ( $ x = 0 ; $ x < $ half_x ; ++ $ x ) { imagecopy ( $ temp_image , $ image , 0 , 0 , $ x , 0 , 1 , $ sy ) ; imagecopy ( $ image , $ image , $ x , 0 , $ max_x - $ x , 0 , 1 , $ sy ) ; imagecopy ( $ image , $ temp_image , $ max_x - $ x , 0 , 0 , 0 , 1 , $ sy ) ; } break ; } case self :: IMG_FLIP_VERTICAL : { $ sx = imagesx ( $ image ) ; $ max_y = imagesy ( $ image ) - 1 ; $ half_y = $ max_y / 2 ; $ temp_image = imageistruecolor ( $ image ) ? imagecreatetruecolor ( $ sx , 1 ) : imagecreate ( $ sx , 1 ) ; for ( $ y = 0 ; $ y < $ half_y ; ++ $ y ) { imagecopy ( $ temp_image , $ image , 0 , 0 , 0 , $ y , $ sx , 1 ) ; imagecopy ( $ image , $ image , 0 , $ y , 0 , $ max_y - $ y , $ sx , 1 ) ; imagecopy ( $ image , $ temp_image , 0 , $ max_y - $ y , 0 , 0 , $ sx , 1 ) ; } break ; } case self :: IMG_FLIP_BOTH : { $ sx = imagesx ( $ image ) ; $ sy = imagesy ( $ image ) ; $ temp_image = imagerotate ( $ image , 180 , 0 ) ; imagecopy ( $ image , $ temp_image , 0 , 0 , 0 , 0 , $ sx , $ sy ) ; break ; } default : return null ; } imagedestroy ( $ temp_image ) ; }
|
Flips an image using a given mode if PHP version is lower than 5 . 5
|
7,530
|
public function register ( $ email , $ password , $ username = null , callable $ callback = null ) { $ this -> throttle ( [ 'enumerateUsers' , $ this -> getIpAddress ( ) ] , 1 , ( 60 * 60 ) , 75 ) ; $ this -> throttle ( [ 'createNewAccount' , $ this -> getIpAddress ( ) ] , 1 , ( 60 * 60 * 12 ) , 5 , true ) ; $ newUserId = $ this -> createUserInternal ( false , $ email , $ password , $ username , $ callback ) ; $ this -> throttle ( [ 'createNewAccount' , $ this -> getIpAddress ( ) ] , 1 , ( 60 * 60 * 12 ) , 5 , false ) ; return $ newUserId ; }
|
Attempts to sign up a user
|
7,531
|
public function login ( $ email , $ password , $ rememberDuration = null , callable $ onBeforeSuccess = null ) { $ this -> throttle ( [ 'attemptToLogin' , 'email' , $ email ] , 500 , ( 60 * 60 * 24 ) , null , true ) ; $ this -> authenticateUserInternal ( $ password , $ email , null , $ rememberDuration , $ onBeforeSuccess ) ; }
|
Attempts to sign in a user with their email address and password
|
7,532
|
public function loginWithUsername ( $ username , $ password , $ rememberDuration = null , callable $ onBeforeSuccess = null ) { $ this -> throttle ( [ 'attemptToLogin' , 'username' , $ username ] , 500 , ( 60 * 60 * 24 ) , null , true ) ; $ this -> authenticateUserInternal ( $ password , null , $ username , $ rememberDuration , $ onBeforeSuccess ) ; }
|
Attempts to sign in a user with their username and password
|
7,533
|
public function reconfirmPassword ( $ password ) { if ( $ this -> isLoggedIn ( ) ) { try { $ password = self :: validatePassword ( $ password ) ; } catch ( InvalidPasswordException $ e ) { return false ; } $ this -> throttle ( [ 'reconfirmPassword' , $ this -> getIpAddress ( ) ] , 3 , ( 60 * 60 ) , 4 , true ) ; try { $ expectedHash = $ this -> db -> selectValue ( 'SELECT password FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE id = ?' , [ $ this -> getUserId ( ) ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } if ( ! empty ( $ expectedHash ) ) { $ validated = \ password_verify ( $ password , $ expectedHash ) ; if ( ! $ validated ) { $ this -> throttle ( [ 'reconfirmPassword' , $ this -> getIpAddress ( ) ] , 3 , ( 60 * 60 ) , 4 , false ) ; } return $ validated ; } else { throw new NotLoggedInException ( ) ; } } else { throw new NotLoggedInException ( ) ; } }
|
Attempts to confirm the currently signed - in user s password again
|
7,534
|
public function logOut ( ) { if ( $ this -> isLoggedIn ( ) ) { $ rememberDirectiveSelector = $ this -> getRememberDirectiveSelector ( ) ; if ( isset ( $ rememberDirectiveSelector ) ) { $ this -> deleteRememberDirectiveForUserById ( $ this -> getUserId ( ) , $ rememberDirectiveSelector ) ; } unset ( $ _SESSION [ self :: SESSION_FIELD_LOGGED_IN ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_USER_ID ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_EMAIL ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_USERNAME ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_STATUS ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_ROLES ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_REMEMBERED ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_LAST_RESYNC ] ) ; unset ( $ _SESSION [ self :: SESSION_FIELD_FORCE_LOGOUT ] ) ; } }
|
Logs the user out
|
7,535
|
public function logOutEverywhere ( ) { if ( ! $ this -> isLoggedIn ( ) ) { throw new NotLoggedInException ( ) ; } $ this -> forceLogoutForUserById ( $ this -> getUserId ( ) ) ; $ this -> logOut ( ) ; }
|
Logs the user out in all sessions
|
7,536
|
private function setRememberCookie ( $ selector , $ token , $ expires ) { $ params = \ session_get_cookie_params ( ) ; if ( isset ( $ selector ) && isset ( $ token ) ) { $ content = $ selector . self :: COOKIE_CONTENT_SEPARATOR . $ token ; } else { $ content = '' ; } $ cookie = new Cookie ( $ this -> rememberCookieName ) ; $ cookie -> setValue ( $ content ) ; $ cookie -> setExpiryTime ( $ expires ) ; $ cookie -> setPath ( $ params [ 'path' ] ) ; $ cookie -> setDomain ( $ params [ 'domain' ] ) ; $ cookie -> setHttpOnly ( $ params [ 'httponly' ] ) ; $ cookie -> setSecureOnly ( $ params [ 'secure' ] ) ; $ result = $ cookie -> save ( ) ; if ( $ result === false ) { throw new HeadersAlreadySentError ( ) ; } if ( ! isset ( $ selector ) || ! isset ( $ token ) ) { $ cookie = new Cookie ( 'auth_remember' ) ; $ cookie -> setPath ( ( ! empty ( $ params [ 'path' ] ) ) ? $ params [ 'path' ] : '/' ) ; $ cookie -> setDomain ( $ params [ 'domain' ] ) ; $ cookie -> setHttpOnly ( $ params [ 'httponly' ] ) ; $ cookie -> setSecureOnly ( $ params [ 'secure' ] ) ; $ cookie -> delete ( ) ; } }
|
Sets or updates the cookie that manages the remember me token
|
7,537
|
private function deleteSessionCookie ( ) { $ params = \ session_get_cookie_params ( ) ; $ cookie = new Cookie ( \ session_name ( ) ) ; $ cookie -> setPath ( $ params [ 'path' ] ) ; $ cookie -> setDomain ( $ params [ 'domain' ] ) ; $ cookie -> setHttpOnly ( $ params [ 'httponly' ] ) ; $ cookie -> setSecureOnly ( $ params [ 'secure' ] ) ; $ result = $ cookie -> delete ( ) ; if ( $ result === false ) { throw new HeadersAlreadySentError ( ) ; } }
|
Deletes the session cookie on the client
|
7,538
|
public function changePassword ( $ oldPassword , $ newPassword ) { if ( $ this -> reconfirmPassword ( $ oldPassword ) ) { $ this -> changePasswordWithoutOldPassword ( $ newPassword ) ; } else { throw new InvalidPasswordException ( ) ; } }
|
Changes the currently signed - in user s password while requiring the old password for verification
|
7,539
|
public function changePasswordWithoutOldPassword ( $ newPassword ) { if ( $ this -> isLoggedIn ( ) ) { $ newPassword = self :: validatePassword ( $ newPassword ) ; $ this -> updatePasswordInternal ( $ this -> getUserId ( ) , $ newPassword ) ; try { $ this -> logOutEverywhereElse ( ) ; } catch ( NotLoggedInException $ ignored ) { } } else { throw new NotLoggedInException ( ) ; } }
|
Changes the currently signed - in user s password without requiring the old password for verification
|
7,540
|
public function resendConfirmationForEmail ( $ email , callable $ callback ) { $ this -> throttle ( [ 'enumerateUsers' , $ this -> getIpAddress ( ) ] , 1 , ( 60 * 60 ) , 75 ) ; $ this -> resendConfirmationForColumnValue ( 'email' , $ email , $ callback ) ; }
|
Attempts to re - send an earlier confirmation request for the user with the specified email address
|
7,541
|
private function resendConfirmationForColumnValue ( $ columnName , $ columnValue , callable $ callback ) { try { $ latestAttempt = $ this -> db -> selectRow ( 'SELECT user_id, email FROM ' . $ this -> makeTableName ( 'users_confirmations' ) . ' WHERE ' . $ columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0' , [ $ columnValue ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } if ( $ latestAttempt === null ) { throw new ConfirmationRequestNotFound ( ) ; } $ this -> throttle ( [ 'resendConfirmation' , 'userId' , $ latestAttempt [ 'user_id' ] ] , 1 , ( 60 * 60 * 6 ) ) ; $ this -> throttle ( [ 'resendConfirmation' , $ this -> getIpAddress ( ) ] , 4 , ( 60 * 60 * 24 * 7 ) , 2 ) ; $ this -> createConfirmationRequest ( $ latestAttempt [ 'user_id' ] , $ latestAttempt [ 'email' ] , $ callback ) ; }
|
Attempts to re - send an earlier confirmation request
|
7,542
|
public function forgotPassword ( $ email , callable $ callback , $ requestExpiresAfter = null , $ maxOpenRequests = null ) { $ email = self :: validateEmailAddress ( $ email ) ; $ this -> throttle ( [ 'enumerateUsers' , $ this -> getIpAddress ( ) ] , 1 , ( 60 * 60 ) , 75 ) ; if ( $ requestExpiresAfter === null ) { $ requestExpiresAfter = 60 * 60 * 6 ; } else { $ requestExpiresAfter = ( int ) $ requestExpiresAfter ; } if ( $ maxOpenRequests === null ) { $ maxOpenRequests = 2 ; } else { $ maxOpenRequests = ( int ) $ maxOpenRequests ; } $ userData = $ this -> getUserDataByEmailAddress ( $ email , [ 'id' , 'verified' , 'resettable' ] ) ; if ( ( int ) $ userData [ 'verified' ] !== 1 ) { throw new EmailNotVerifiedException ( ) ; } if ( ( int ) $ userData [ 'resettable' ] !== 1 ) { throw new ResetDisabledException ( ) ; } $ openRequests = ( int ) $ this -> getOpenPasswordResetRequests ( $ userData [ 'id' ] ) ; if ( $ openRequests < $ maxOpenRequests ) { $ this -> throttle ( [ 'requestPasswordReset' , $ this -> getIpAddress ( ) ] , 4 , ( 60 * 60 * 24 * 7 ) , 2 ) ; $ this -> throttle ( [ 'requestPasswordReset' , 'user' , $ userData [ 'id' ] ] , 4 , ( 60 * 60 * 24 * 7 ) , 2 ) ; $ this -> createPasswordResetRequest ( $ userData [ 'id' ] , $ requestExpiresAfter , $ callback ) ; } else { throw new TooManyRequestsException ( '' , $ requestExpiresAfter ) ; } }
|
Initiates a password reset request for the user with the specified email address
|
7,543
|
private function getOpenPasswordResetRequests ( $ userId ) { try { $ requests = $ this -> db -> selectValue ( 'SELECT COUNT(*) FROM ' . $ this -> makeTableName ( 'users_resets' ) . ' WHERE user = ? AND expires > ?' , [ $ userId , \ time ( ) ] ) ; if ( ! empty ( $ requests ) ) { return $ requests ; } else { return 0 ; } } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } }
|
Returns the number of open requests for a password reset by the specified user
|
7,544
|
private function createPasswordResetRequest ( $ userId , $ expiresAfter , callable $ callback ) { $ selector = self :: createRandomString ( 20 ) ; $ token = self :: createRandomString ( 20 ) ; $ tokenHashed = \ password_hash ( $ token , \ PASSWORD_DEFAULT ) ; $ expiresAt = \ time ( ) + $ expiresAfter ; try { $ this -> db -> insert ( $ this -> makeTableNameComponents ( 'users_resets' ) , [ 'user' => $ userId , 'selector' => $ selector , 'token' => $ tokenHashed , 'expires' => $ expiresAt ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } if ( \ is_callable ( $ callback ) ) { $ callback ( $ selector , $ token ) ; } else { throw new MissingCallbackError ( ) ; } }
|
Creates a new password reset request
|
7,545
|
public function setPasswordResetEnabled ( $ enabled ) { $ enabled = ( bool ) $ enabled ; if ( $ this -> isLoggedIn ( ) ) { try { $ this -> db -> update ( $ this -> makeTableNameComponents ( 'users' ) , [ 'resettable' => $ enabled ? 1 : 0 ] , [ 'id' => $ this -> getUserId ( ) ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } } else { throw new NotLoggedInException ( ) ; } }
|
Sets whether password resets should be permitted for the account of the currently signed - in user
|
7,546
|
public function isPasswordResetEnabled ( ) { if ( $ this -> isLoggedIn ( ) ) { try { $ enabled = $ this -> db -> selectValue ( 'SELECT resettable FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE id = ?' , [ $ this -> getUserId ( ) ] ) ; return ( int ) $ enabled === 1 ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } } else { throw new NotLoggedInException ( ) ; } }
|
Returns whether password resets are permitted for the account of the currently signed - in user
|
7,547
|
public function isLoggedIn ( ) { return isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_LOGGED_IN ] ) && $ _SESSION [ self :: SESSION_FIELD_LOGGED_IN ] === true ; }
|
Returns whether the user is currently logged in by reading from the session
|
7,548
|
public function getUserId ( ) { if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_USER_ID ] ) ) { return $ _SESSION [ self :: SESSION_FIELD_USER_ID ] ; } else { return null ; } }
|
Returns the currently signed - in user s ID by reading from the session
|
7,549
|
public function getEmail ( ) { if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_EMAIL ] ) ) { return $ _SESSION [ self :: SESSION_FIELD_EMAIL ] ; } else { return null ; } }
|
Returns the currently signed - in user s email address by reading from the session
|
7,550
|
public function getUsername ( ) { if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_USERNAME ] ) ) { return $ _SESSION [ self :: SESSION_FIELD_USERNAME ] ; } else { return null ; } }
|
Returns the currently signed - in user s display name by reading from the session
|
7,551
|
public function getStatus ( ) { if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_STATUS ] ) ) { return $ _SESSION [ self :: SESSION_FIELD_STATUS ] ; } else { return null ; } }
|
Returns the currently signed - in user s status by reading from the session
|
7,552
|
public function hasRole ( $ role ) { if ( empty ( $ role ) || ! \ is_numeric ( $ role ) ) { return false ; } if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_ROLES ] ) ) { $ role = ( int ) $ role ; return ( ( ( int ) $ _SESSION [ self :: SESSION_FIELD_ROLES ] ) & $ role ) === $ role ; } else { return false ; } }
|
Returns whether the currently signed - in user has the specified role
|
7,553
|
public function isRemembered ( ) { if ( isset ( $ _SESSION ) && isset ( $ _SESSION [ self :: SESSION_FIELD_REMEMBERED ] ) ) { return $ _SESSION [ self :: SESSION_FIELD_REMEMBERED ] ; } else { return null ; } }
|
Returns whether the currently signed - in user has been remembered by a long - lived cookie
|
7,554
|
public static function createUuid ( ) { $ data = \ openssl_random_pseudo_bytes ( 16 ) ; $ data [ 6 ] = \ chr ( \ ord ( $ data [ 6 ] ) & 0x0f | 0x40 ) ; $ data [ 8 ] = \ chr ( \ ord ( $ data [ 8 ] ) & 0x3f | 0x80 ) ; return \ vsprintf ( '%s%s-%s-%s-%s-%s%s%s' , \ str_split ( \ bin2hex ( $ data ) , 4 ) ) ; }
|
Creates a UUID v4 as per RFC 4122
|
7,555
|
public static function createCookieName ( $ descriptor , $ seed = null ) { $ seed = ( $ seed !== null ) ? $ seed : \ time ( ) ; foreach ( self :: COOKIE_PREFIXES as $ cookiePrefix ) { if ( \ strpos ( $ seed , $ cookiePrefix ) === 0 ) { $ descriptor = $ cookiePrefix . $ descriptor ; } } $ token = Base64 :: encodeUrlSafeWithoutPadding ( \ md5 ( __NAMESPACE__ . "\n" . $ seed , true ) ) ; return $ descriptor . '_' . $ token ; }
|
Generates a unique cookie name for the given descriptor based on the supplied seed
|
7,556
|
private function getRememberDirectiveSelector ( ) { if ( isset ( $ _COOKIE [ $ this -> rememberCookieName ] ) ) { $ selectorAndToken = \ explode ( self :: COOKIE_CONTENT_SEPARATOR , $ _COOKIE [ $ this -> rememberCookieName ] , 2 ) ; return $ selectorAndToken [ 0 ] ; } else { return null ; } }
|
Returns the selector of a potential locally existing remember directive
|
7,557
|
private function getRememberDirectiveExpiry ( ) { if ( $ this -> isLoggedIn ( ) ) { $ existingSelector = $ this -> getRememberDirectiveSelector ( ) ; if ( isset ( $ existingSelector ) ) { $ existingExpiry = $ this -> db -> selectValue ( 'SELECT expires FROM ' . $ this -> makeTableName ( 'users_remembered' ) . ' WHERE selector = ? AND user = ?' , [ $ existingSelector , $ this -> getUserId ( ) ] ) ; if ( isset ( $ existingExpiry ) ) { return ( int ) $ existingExpiry ; } } } return null ; }
|
Returns the expiry date of a potential locally existing remember directive
|
7,558
|
public static function createRandomString ( $ maxLength = 24 ) { $ bytes = \ floor ( ( int ) $ maxLength / 4 ) * 3 ; $ data = \ openssl_random_pseudo_bytes ( $ bytes ) ; return Base64 :: encodeUrlSafe ( $ data ) ; }
|
Creates a random string with the given maximum length
|
7,559
|
protected function updatePasswordInternal ( $ userId , $ newPassword ) { $ newPassword = \ password_hash ( $ newPassword , \ PASSWORD_DEFAULT ) ; try { $ affected = $ this -> db -> update ( $ this -> makeTableNameComponents ( 'users' ) , [ 'password' => $ newPassword ] , [ 'id' => $ userId ] ) ; if ( $ affected === 0 ) { throw new UnknownIdException ( ) ; } } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } }
|
Updates the given user s password by setting it to the new specified password
|
7,560
|
protected function onLoginSuccessful ( $ userId , $ email , $ username , $ status , $ roles , $ forceLogout , $ remembered ) { Session :: regenerate ( true ) ; $ _SESSION [ self :: SESSION_FIELD_LOGGED_IN ] = true ; $ _SESSION [ self :: SESSION_FIELD_USER_ID ] = ( int ) $ userId ; $ _SESSION [ self :: SESSION_FIELD_EMAIL ] = $ email ; $ _SESSION [ self :: SESSION_FIELD_USERNAME ] = $ username ; $ _SESSION [ self :: SESSION_FIELD_STATUS ] = ( int ) $ status ; $ _SESSION [ self :: SESSION_FIELD_ROLES ] = ( int ) $ roles ; $ _SESSION [ self :: SESSION_FIELD_FORCE_LOGOUT ] = ( int ) $ forceLogout ; $ _SESSION [ self :: SESSION_FIELD_REMEMBERED ] = $ remembered ; $ _SESSION [ self :: SESSION_FIELD_LAST_RESYNC ] = \ time ( ) ; }
|
Called when a user has successfully logged in
|
7,561
|
protected static function validatePassword ( $ password ) { if ( empty ( $ password ) ) { throw new InvalidPasswordException ( ) ; } $ password = \ trim ( $ password ) ; if ( \ strlen ( $ password ) < 1 ) { throw new InvalidPasswordException ( ) ; } return $ password ; }
|
Validates a password
|
7,562
|
protected function createConfirmationRequest ( $ userId , $ email , callable $ callback ) { $ selector = self :: createRandomString ( 16 ) ; $ token = self :: createRandomString ( 16 ) ; $ tokenHashed = \ password_hash ( $ token , \ PASSWORD_DEFAULT ) ; $ expires = \ time ( ) + 60 * 60 * 24 ; try { $ this -> db -> insert ( $ this -> makeTableNameComponents ( 'users_confirmations' ) , [ 'user_id' => ( int ) $ userId , 'email' => $ email , 'selector' => $ selector , 'token' => $ tokenHashed , 'expires' => $ expires ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } if ( \ is_callable ( $ callback ) ) { $ callback ( $ selector , $ token ) ; } else { throw new MissingCallbackError ( ) ; } }
|
Creates a request for email confirmation
|
7,563
|
protected function forceLogoutForUserById ( $ userId ) { $ this -> deleteRememberDirectiveForUserById ( $ userId ) ; $ this -> db -> exec ( 'UPDATE ' . $ this -> makeTableName ( 'users' ) . ' SET force_logout = force_logout + 1 WHERE id = ?' , [ $ userId ] ) ; }
|
Triggers a forced logout in all sessions that belong to the specified user
|
7,564
|
public function createUserWithUniqueUsername ( $ email , $ password , $ username = null ) { return $ this -> createUserInternal ( true , $ email , $ password , $ username , null ) ; }
|
Creates a new user while ensuring that the username is unique
|
7,565
|
public function deleteUserByEmail ( $ email ) { $ email = self :: validateEmailAddress ( $ email ) ; $ numberOfDeletedUsers = $ this -> deleteUsersByColumnValue ( 'email' , $ email ) ; if ( $ numberOfDeletedUsers === 0 ) { throw new InvalidEmailException ( ) ; } }
|
Deletes the user with the specified email address
|
7,566
|
public function deleteUserByUsername ( $ username ) { $ userData = $ this -> getUserDataByUsername ( \ trim ( $ username ) , [ 'id' ] ) ; $ this -> deleteUsersByColumnValue ( 'id' , ( int ) $ userData [ 'id' ] ) ; }
|
Deletes the user with the specified username
|
7,567
|
public function addRoleForUserById ( $ userId , $ role ) { $ userFound = $ this -> addRoleForUserByColumnValue ( 'id' , ( int ) $ userId , $ role ) ; if ( $ userFound === false ) { throw new UnknownIdException ( ) ; } }
|
Assigns the specified role to the user with the given ID
|
7,568
|
public function addRoleForUserByEmail ( $ userEmail , $ role ) { $ userEmail = self :: validateEmailAddress ( $ userEmail ) ; $ userFound = $ this -> addRoleForUserByColumnValue ( 'email' , $ userEmail , $ role ) ; if ( $ userFound === false ) { throw new InvalidEmailException ( ) ; } }
|
Assigns the specified role to the user with the given email address
|
7,569
|
public function addRoleForUserByUsername ( $ username , $ role ) { $ userData = $ this -> getUserDataByUsername ( \ trim ( $ username ) , [ 'id' ] ) ; $ this -> addRoleForUserByColumnValue ( 'id' , ( int ) $ userData [ 'id' ] , $ role ) ; }
|
Assigns the specified role to the user with the given username
|
7,570
|
public function removeRoleForUserById ( $ userId , $ role ) { $ userFound = $ this -> removeRoleForUserByColumnValue ( 'id' , ( int ) $ userId , $ role ) ; if ( $ userFound === false ) { throw new UnknownIdException ( ) ; } }
|
Takes away the specified role from the user with the given ID
|
7,571
|
public function removeRoleForUserByEmail ( $ userEmail , $ role ) { $ userEmail = self :: validateEmailAddress ( $ userEmail ) ; $ userFound = $ this -> removeRoleForUserByColumnValue ( 'email' , $ userEmail , $ role ) ; if ( $ userFound === false ) { throw new InvalidEmailException ( ) ; } }
|
Takes away the specified role from the user with the given email address
|
7,572
|
public function removeRoleForUserByUsername ( $ username , $ role ) { $ userData = $ this -> getUserDataByUsername ( \ trim ( $ username ) , [ 'id' ] ) ; $ this -> removeRoleForUserByColumnValue ( 'id' , ( int ) $ userData [ 'id' ] , $ role ) ; }
|
Takes away the specified role from the user with the given username
|
7,573
|
public function doesUserHaveRole ( $ userId , $ role ) { if ( empty ( $ role ) || ! \ is_numeric ( $ role ) ) { return false ; } $ userId = ( int ) $ userId ; $ rolesBitmask = $ this -> db -> selectValue ( 'SELECT roles_mask FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE id = ?' , [ $ userId ] ) ; if ( $ rolesBitmask === null ) { throw new UnknownIdException ( ) ; } $ role = ( int ) $ role ; return ( $ rolesBitmask & $ role ) === $ role ; }
|
Returns whether the user with the given ID has the specified role
|
7,574
|
public function getRolesForUserById ( $ userId ) { $ userId = ( int ) $ userId ; $ rolesBitmask = $ this -> db -> selectValue ( 'SELECT roles_mask FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE id = ?' , [ $ userId ] ) ; if ( $ rolesBitmask === null ) { throw new UnknownIdException ( ) ; } return \ array_filter ( Role :: getMap ( ) , function ( $ each ) use ( $ rolesBitmask ) { return ( $ rolesBitmask & $ each ) === $ each ; } , \ ARRAY_FILTER_USE_KEY ) ; }
|
Returns the roles of the user with the given ID mapping the numerical values to their descriptive names
|
7,575
|
public function logInAsUserByEmail ( $ email ) { $ email = self :: validateEmailAddress ( $ email ) ; $ numberOfMatchedUsers = $ this -> logInAsUserByColumnValue ( 'email' , $ email ) ; if ( $ numberOfMatchedUsers === 0 ) { throw new InvalidEmailException ( ) ; } }
|
Signs in as the user with the specified email address
|
7,576
|
public function logInAsUserByUsername ( $ username ) { $ numberOfMatchedUsers = $ this -> logInAsUserByColumnValue ( 'username' , \ trim ( $ username ) ) ; if ( $ numberOfMatchedUsers === 0 ) { throw new UnknownUsernameException ( ) ; } elseif ( $ numberOfMatchedUsers > 1 ) { throw new AmbiguousUsernameException ( ) ; } }
|
Signs in as the user with the specified display name
|
7,577
|
public function changePasswordForUserById ( $ userId , $ newPassword ) { $ userId = ( int ) $ userId ; $ newPassword = self :: validatePassword ( $ newPassword ) ; $ this -> updatePasswordInternal ( $ userId , $ newPassword ) ; $ this -> forceLogoutForUserById ( $ userId ) ; }
|
Changes the password for the user with the given ID
|
7,578
|
public function changePasswordForUserByUsername ( $ username , $ newPassword ) { $ userData = $ this -> getUserDataByUsername ( \ trim ( $ username ) , [ 'id' ] ) ; $ this -> changePasswordForUserById ( ( int ) $ userData [ 'id' ] , $ newPassword ) ; }
|
Changes the password for the user with the given username
|
7,579
|
private function deleteUsersByColumnValue ( $ columnName , $ columnValue ) { try { return $ this -> db -> delete ( $ this -> makeTableNameComponents ( 'users' ) , [ $ columnName => $ columnValue ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } }
|
Deletes all existing users where the column with the specified name has the given value
|
7,580
|
private function modifyRolesForUserByColumnValue ( $ columnName , $ columnValue , callable $ modification ) { try { $ userData = $ this -> db -> selectRow ( 'SELECT id, roles_mask FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE ' . $ columnName . ' = ?' , [ $ columnValue ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } if ( $ userData === null ) { return false ; } $ newRolesBitmask = $ modification ( $ userData [ 'roles_mask' ] ) ; try { $ this -> db -> exec ( 'UPDATE ' . $ this -> makeTableName ( 'users' ) . ' SET roles_mask = ? WHERE id = ?' , [ $ newRolesBitmask , ( int ) $ userData [ 'id' ] ] ) ; return true ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } }
|
Modifies the roles for the user where the column with the specified name has the given value
|
7,581
|
private function addRoleForUserByColumnValue ( $ columnName , $ columnValue , $ role ) { $ role = ( int ) $ role ; return $ this -> modifyRolesForUserByColumnValue ( $ columnName , $ columnValue , function ( $ oldRolesBitmask ) use ( $ role ) { return $ oldRolesBitmask | $ role ; } ) ; }
|
Assigns the specified role to the user where the column with the specified name has the given value
|
7,582
|
private function removeRoleForUserByColumnValue ( $ columnName , $ columnValue , $ role ) { $ role = ( int ) $ role ; return $ this -> modifyRolesForUserByColumnValue ( $ columnName , $ columnValue , function ( $ oldRolesBitmask ) use ( $ role ) { return $ oldRolesBitmask & ~ $ role ; } ) ; }
|
Takes away the specified role from the user where the column with the specified name has the given value
|
7,583
|
private function logInAsUserByColumnValue ( $ columnName , $ columnValue ) { try { $ users = $ this -> db -> select ( 'SELECT verified, id, email, username, status, roles_mask FROM ' . $ this -> makeTableName ( 'users' ) . ' WHERE ' . $ columnName . ' = ? LIMIT 2 OFFSET 0' , [ $ columnValue ] ) ; } catch ( Error $ e ) { throw new DatabaseError ( $ e -> getMessage ( ) ) ; } $ numberOfMatchingUsers = ( $ users !== null ) ? \ count ( $ users ) : 0 ; if ( $ numberOfMatchingUsers === 1 ) { $ user = $ users [ 0 ] ; if ( ( int ) $ user [ 'verified' ] === 1 ) { $ this -> onLoginSuccessful ( $ user [ 'id' ] , $ user [ 'email' ] , $ user [ 'username' ] , $ user [ 'status' ] , $ user [ 'roles_mask' ] , \ PHP_INT_MAX , false ) ; } else { throw new EmailNotVerifiedException ( ) ; } } return $ numberOfMatchingUsers ; }
|
Signs in as the user for which the column with the specified name has the given value
|
7,584
|
public function _extractLocations ( $ words , $ fulltext ) { $ locations = array ( ) ; foreach ( $ words as $ word ) { $ wordlen = strlen ( $ word ) ; $ loc = stripos ( $ fulltext , $ word ) ; while ( $ loc !== false ) { $ locations [ ] = $ loc ; $ loc = stripos ( $ fulltext , $ word , $ loc + $ wordlen ) ; } } $ locations = array_unique ( $ locations ) ; sort ( $ locations ) ; return $ locations ; }
|
find the locations of each of the words Nothing exciting here . The array_unique is required unless you decide to make the words unique before passing in
|
7,585
|
private static function m ( $ str ) { $ c = self :: $ regex_consonant ; $ v = self :: $ regex_vowel ; $ str = preg_replace ( "#^$c+#" , '' , $ str ) ; $ str = preg_replace ( "#$v+$#" , '' , $ str ) ; preg_match_all ( "#($v+$c+)#" , $ str , $ matches ) ; return count ( $ matches [ 1 ] ) ; }
|
What you mean it s not obvious from the name?
|
7,586
|
public function findNearest ( $ currentLocation , $ distance , $ limit = 10 ) { $ startTimer = microtime ( true ) ; $ res = $ this -> buildQuery ( $ currentLocation , $ distance , $ limit ) ; $ stopTimer = microtime ( true ) ; return [ 'ids' => $ res -> pluck ( 'doc_id' ) , 'distances' => $ res -> pluck ( 'distance' ) , 'hits' => $ res -> count ( ) , 'execution_time' => round ( $ stopTimer - $ startTimer , 7 ) * 1000 . " ms" ] ; }
|
Distance is in KM
|
7,587
|
public static function stem ( $ word ) { $ nounStem = self :: roughStem ( $ word , self :: $ _nounMay , self :: $ _nounPre , self :: $ _nounPost , self :: $ _nounMaxPre , self :: $ _nounMaxPost , self :: $ _nounMinStem ) ; $ verbStem = self :: roughStem ( $ word , self :: $ _verbMay , self :: $ _verbPre , self :: $ _verbPost , self :: $ _verbMaxPre , self :: $ _verbMaxPost , self :: $ _verbMinStem ) ; if ( mb_strlen ( $ nounStem , 'UTF-8' ) < mb_strlen ( $ verbStem , 'UTF-8' ) ) { $ stem = $ nounStem ; } else { $ stem = $ verbStem ; } return $ stem ; }
|
Get rough stem of the given Arabic word
|
7,588
|
private static function step0a ( $ word ) { $ vstr = implode ( '' , self :: $ vowels ) ; $ word = preg_replace ( '#([' . $ vstr . '])u([' . $ vstr . '])#u' , '$1U$2' , $ word ) ; $ word = preg_replace ( '#([' . $ vstr . '])y([' . $ vstr . '])#u' , '$1Y$2' , $ word ) ; return $ word ; }
|
Replaces to protect some characters
|
7,589
|
public function loadAndResolveFile ( ) : \ SimpleXMLElement { $ content = \ file_get_contents ( $ this -> path ) ; $ strpos = \ strpos ( $ content , '?>' ) + 2 ; if ( ! \ file_exists ( __DIR__ . '/../doc/entities/generated.ent' ) ) { self :: buildEntities ( ) ; } $ path = \ realpath ( __DIR__ . '/../doc/entities/generated.ent' ) ; $ content = \ substr ( $ content , 0 , $ strpos ) . '<!DOCTYPE refentry SYSTEM "' . $ path . '">' . \ substr ( $ content , $ strpos + 1 ) ; echo 'Loading ' . $ this -> path . "\n" ; $ elem = \ simplexml_load_string ( $ content , \ SimpleXMLElement :: class , LIBXML_DTDLOAD | LIBXML_NOENT ) ; if ( $ elem === false ) { throw new \ RuntimeException ( 'Invalid XML file for ' . $ this -> path ) ; } $ elem -> registerXPathNamespace ( 'docbook' , 'http://docbook.org/ns/docbook' ) ; return $ elem ; }
|
Loads the XML file resolving all DTD declared entities .
|
7,590
|
private static function isClass ( string $ type ) : bool { if ( $ type === '' ) { throw new EmptyTypeException ( 'Empty type passed' ) ; } if ( $ type === 'stdClass' ) { return true ; } if ( $ type [ 0 ] === strtoupper ( $ type [ 0 ] ) ) { return true ; } return false ; }
|
Returns true if the type passed in parameter is a class false if it is scalar or resource
|
7,591
|
private function removeString ( string $ string , string $ search ) : string { $ search = str_replace ( ' ' , '\s+' , $ search ) ; $ result = preg_replace ( '/[\s\,]*' . $ search . '/m' , '' , $ string ) ; if ( $ result === null ) { throw new \ RuntimeException ( 'An error occurred while calling preg_replace' ) ; } return $ result ; }
|
Removes a string even if the string is split on multiple lines .
|
7,592
|
public function isOverloaded ( ) : bool { foreach ( $ this -> getParams ( ) as $ parameter ) { if ( $ parameter -> isOptionalWithNoDefault ( ) && ! $ parameter -> isByReference ( ) ) { return true ; } } return false ; }
|
The function is overloaded if at least one parameter is optional with no default value and this parameter is not by reference .
|
7,593
|
private function getIgnoredFunctions ( ) : array { if ( $ this -> ignoredFunctions === null ) { $ ignoredFunctions = require __DIR__ . '/../config/ignoredFunctions.php' ; $ specialCaseFunctions = require __DIR__ . '/../config/specialCasesFunctions.php' ; $ this -> ignoredFunctions = array_merge ( $ ignoredFunctions , $ specialCaseFunctions ) ; } return $ this -> ignoredFunctions ; }
|
Returns the list of functions that must be ignored .
|
7,594
|
public function generateXlsFile ( array $ protoFunctions , string $ path ) : void { $ spreadsheet = new Spreadsheet ( ) ; $ numb = 1 ; $ sheet = $ spreadsheet -> getActiveSheet ( ) ; $ sheet -> setCellValue ( 'A1' , 'Function name' ) ; $ sheet -> setCellValue ( 'B1' , 'Status' ) ; foreach ( $ protoFunctions as $ protoFunction ) { if ( $ protoFunction ) { if ( strpos ( $ protoFunction , '=' ) === false && strpos ( $ protoFunction , 'json' ) === false ) { $ status = 'classic' ; } elseif ( strpos ( $ protoFunction , 'json' ) ) { $ status = 'json' ; } else { $ status = 'opt' ; } $ sheet -> setCellValue ( 'A' . $ numb , $ protoFunction ) ; $ sheet -> setCellValue ( 'B' . $ numb ++ , $ status ) ; } } $ writer = new Xlsx ( $ spreadsheet ) ; $ writer -> save ( $ path ) ; }
|
This function generate an xls file
|
7,595
|
public function generatePhpFile ( array $ functions , string $ path ) : void { $ path = rtrim ( $ path , '/' ) . '/' ; $ phpFunctionsByModule = [ ] ; foreach ( $ functions as $ function ) { $ writePhpFunction = new WritePhpFunction ( $ function ) ; $ phpFunctionsByModule [ $ function -> getModuleName ( ) ] [ ] = $ writePhpFunction -> getPhpFunctionalFunction ( ) ; } foreach ( $ phpFunctionsByModule as $ module => $ phpFunctions ) { $ lcModule = \ lcfirst ( $ module ) ; $ stream = \ fopen ( $ path . $ lcModule . '.php' , 'w' ) ; if ( $ stream === false ) { throw new \ RuntimeException ( 'Unable to write to ' . $ path ) ; } \ fwrite ( $ stream , "<?php\nnamespace Safe;use Safe\\Exceptions\\" . self :: toExceptionName ( $ module ) . ';' ) ; foreach ( $ phpFunctions as $ phpFunction ) { \ fwrite ( $ stream , $ phpFunction . "\n" ) ; } \ fclose ( $ stream ) ; } }
|
This function generate an improved php lib function in a php file
|
7,596
|
public function generateFunctionsList ( array $ functions , string $ path ) : void { $ functionNames = $ this -> getFunctionsNameList ( $ functions ) ; $ stream = fopen ( $ path , 'w' ) ; if ( $ stream === false ) { throw new \ RuntimeException ( 'Unable to write to ' . $ path ) ; } fwrite ( $ stream , "<?php\nreturn [\n" ) ; foreach ( $ functionNames as $ functionName ) { fwrite ( $ stream , ' ' . \ var_export ( $ functionName , true ) . ",\n" ) ; } fwrite ( $ stream , "];\n" ) ; fclose ( $ stream ) ; }
|
This function generate a PHP file containing the list of functions we can handle .
|
7,597
|
public function generateRectorFile ( array $ functions , string $ path ) : void { $ functionNames = $ this -> getFunctionsNameList ( $ functions ) ; $ stream = fopen ( $ path , 'w' ) ; if ( $ stream === false ) { throw new \ RuntimeException ( 'Unable to write to ' . $ path ) ; } fwrite ( $ stream , "# This rector file is replacing all core PHP functions with the equivalent \"safe\" functions# It is targetting Rector 0.4.x versions.# If you are using Rector 0.3, please upgrade your Rector versionservices: Rector\Rector\Function_\RenameFunctionRector: \$oldFunctionToNewFunction:" ) ; foreach ( $ functionNames as $ functionName ) { fwrite ( $ stream , ' ' . $ functionName . ": 'Safe\\" . $ functionName . "'\n" ) ; } fclose ( $ stream ) ; }
|
This function generate a rector yml file containing a replacer for all functions
|
7,598
|
public function getMetadataForFile ( string $ file ) : ? BenchmarkMetadata { $ hierarchy = $ this -> reflector -> reflect ( $ file ) ; if ( $ hierarchy -> isEmpty ( ) ) { return null ; } try { $ top = $ hierarchy -> getTop ( ) ; } catch ( \ InvalidArgumentException $ exception ) { return null ; } if ( true === $ top -> abstract ) { return null ; } $ metadata = $ this -> driver -> getMetadataForHierarchy ( $ hierarchy ) ; $ this -> validateBenchmark ( $ hierarchy , $ metadata ) ; foreach ( $ metadata -> getSubjects ( ) as $ subject ) { $ this -> validateSubject ( $ hierarchy , $ subject ) ; $ paramProviders = $ subject -> getParamProviders ( ) ; $ parameterSets = $ this -> reflector -> getParameterSets ( $ metadata -> getPath ( ) , $ paramProviders ) ; foreach ( $ parameterSets as $ parameterSet ) { if ( ! is_array ( $ parameterSet ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Each parameter set must be an array, got "%s" for %s::%s' , gettype ( $ parameterSet ) , $ metadata -> getClass ( ) , $ subject -> getName ( ) ) ) ; } } $ subject -> setParameterSets ( $ parameterSets ) ; } return $ metadata ; }
|
Return a Benchmark instance for the given file or NULL if the given file contains no classes or the class in the given file is abstract .
|
7,599
|
public function decode ( Document $ document ) { $ suites = [ ] ; foreach ( $ document -> query ( '//suite' ) as $ suiteEl ) { $ suites [ ] = $ this -> processSuite ( $ suiteEl ) ; } return new SuiteCollection ( $ suites ) ; }
|
Decode a PHPBench XML document into a SuiteCollection .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.