예제 #1
0
 public static function attempt($username, $password)
 {
     $log = new Log("ERROR");
     $logInfo = new LOG("INFO");
     if ($username == 'guest' && password_verify($password, self::$password)) {
         $_SESSION['logged_in_user'] = $username;
         $logInfo->logInfo("User " . $username . " is logged in. ");
     } else {
         if ($username != '' && $password != '') {
             $log->logError("login Info incorrect!!");
             echo "You are WRONG!!!!";
         }
     }
 }
예제 #2
0
 public static function init()
 {
     self::$__date = date('Y-m-d H:i:s');
     self::$__log = ['request-time' => self::$__date, 'remote-address' => $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REMOTE_PORT'], 'request-method' => $_SERVER['REQUEST_METHOD'], 'uri' => $_SERVER['REQUEST_URI']];
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         self::$__log['request'] = "\n" . file_get_contents('php://input');
     }
 }
예제 #3
0
 public function run(Request &$request)
 {
     LOG::point(__METHOD__);
     Sokol::checkAccess($this);
     $action = HttpKernel::getAction($this, $request);
     //--- ACTION
     return $this->{$action}($request);
 }
예제 #4
0
 /**
  * Get the article for news message
  *
  * @return mixed 	false if this is not a news | array of articles
  */
 public function articles()
 {
     if ($this->message->msgType !== 'news') {
         LOG::warning('Accessing article for non-news message');
         return false;
     }
     $content = $this->content;
     return $content['Articles'];
 }
예제 #5
0
 public static function assert($truth)
 {
     global $DEBUG_ASSERTS;
     if ($DEBUG_ASSERTS && !$truth) {
         $d_bt = debug_backtrace();
         LOG::fatal("Debug assertion failed at line " . $d_bt[0]['line'] . " of file " . $d_bt[0]['file'] . ".");
         return false;
     }
     return true;
 }
예제 #6
0
 /**
  * @name customLog
  * @desc 记录自定义日志,请注意日志文件大小问题
  * @param string $filename 记录日志的文件名
  * @param string $msg    错误信息
  * @param int $priority  接受的类型
  * LOG_EMERG system is unusable
  * LOG_ALERT action must be taken immediately
  * LOG_CRIT critical conditions
  * LOG_ERR error conditions
  * LOG_WARNING warning conditions
  * LOG_NOTICE normal, but significant, condition
  * LOG_INFO informational message
  * LOG_DEBUG debug-level message
  */
 public static function customLog($filename, $msg, $priority = '')
 {
     $log_obj = LOG::getInstance();
     $string = "";
     $string .= "/*********************** " . $priority . " " . date('Y-m-d H:i:s') . " ***********************/\r\n";
     $string .= $msg . "\r\n";
     $fp = fopen($log_obj->path . DIRECTORY_SEPARATOR . $filename, 'a');
     flock($fp, LOCK_EX);
     fwrite($fp, $string);
     flock($fp, LOCK_UN);
     fclose($fp);
     return true;
 }
예제 #7
0
	function sendmail($to, $from, $personal, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") {
		$subject = $this->getBase64($subject);
		$mail_from = $this->get_address ( $this->strip_comment ( $from ) );
		$body = ereg_replace ( "(^|(\r\n))(\\.)", "\\1.\\3", $body );
		$body = base64_encode($body);
		$toencode = $this->getBase64($to);
		$ccencode = $this->getBase64($cc);
		$personalencode = $this->getBase64($personal);
		$header .= "X-Originating-IP:".get_client_ip()."\r\n";
		$header .= "MIME-Version:1.0\r\n";
		if ($mailtype == "HTML") {
			$header .= "Content-Type:text/html;charset=\"UTF-8\"\r\n";
		}
		$header .= "To: \"" . $toencode . "\" <" . $to . ">;\r\n";
		if ($cc != "") {
			$header .= "Cc: " . $ccencode . "\r\n";
		}
		$header .= "From: \"$personalencode\" <" . $from . ">;\r\n";
		$header .= "Subject: " . $subject . "\r\n";
		$header .= $additional_headers;
		$header .= "Date: " . date ( "r" ) . "\r\n";
		$header .= "X-Mailer:By RJS (PHP/" . phpversion () . ")\r\n";
		list ( $msec, $sec ) = explode ( " ", microtime () );
		$header .= "Message-ID: <" . date ( "YmdHis", $sec ) . "." . ($msec * 1000000) . "." . $mail_from . ">;\r\n";
		$header .= "Content-Transfer-Encoding: base64\r\n";
		$TO = explode ( ",", $this->strip_comment ( $to ) );
		if ($cc != "") {
			$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $cc ) ) );
		}
		if ($bcc != "") {
			$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $bcc ) ) );
		}
		$sent = TRUE;
		foreach ( $TO as $rcpt_to ) {
			$rcpt_to = $this->get_address ( $rcpt_to );
			if (! $this->smtp_sockopen ( $rcpt_to )) {
				LOG::write( "Error: Cannot send email to " . $rcpt_to, LOG::ERR);
				$sent = FALSE;
				continue;
			}
			if ($this->smtp_send ( $this->host_name, $mail_from, $rcpt_to, $header, $body )) {
				LOG::write( "E-mail has been sent to <" . $rcpt_to, LOG::INFO);
			} else {
				LOG::write( "Error: Cannot send email to <" . $rcpt_to, LOG::ERR);
				$sent = FALSE;
			}
			fclose ( $this->sock );
			$this->log_write ( "Disconnected from remote host\n" );
		}
		return $sent;
	}
예제 #8
0
function send_email($bcc_list, $subject, $bb_body, $reply_to = NULL, $prefix = NULL, $footer = NULL, $headers = NULL)
{
    global $EMAIL_ADDRESS, $EMAIL_USERNAME, $EMAIL_PASSWORD, $SMTP_SERVER, $SMTP_SERVER_PORT, $SMTP_SERVER_PROTOCOL, $LMT_EMAIL;
    require_once PATH::lib() . "/swiftmailer/swift_required.php";
    //Instead of using parameter default values, so we can pass NULL. And it's more readable.
    if (count($bcc_list) == 0) {
        return true;
    }
    if (is_null($reply_to)) {
        $reply_to = array($EMAIL_ADDRESS => 'LHS Math Club Mailbot');
    }
    if (is_null($prefix)) {
        $prefix = '[LHS Math Club]';
    }
    if (is_null($footer)) {
        $footer = "LHS Math Club\n[url]" . get_site_url() . "[/url]\nTo stop receiving LHSMATH emails, contact [email]webmaster@lhsmath.org[/email].";
    }
    if (is_null($headers)) {
        $headers = array();
    }
    if (is_string($bcc_list)) {
        $bcc_list = array($bcc_list);
    }
    if (!is_array($bcc_list) || !is_string($subject) || !is_string($bb_body) || !is_array($reply_to) && !is_string($reply_to) || !is_string($prefix) || !is_string($footer) || !is_array($headers)) {
        return 'Invalid email parameters.';
    }
    if (($error_msg = val_email_msg($subject, $bb_body)) !== true) {
        return $error_msg;
    }
    if ($footer != "") {
        $bb_body .= "\n\n\n---\n{$footer}\n";
    }
    //Attach footer.
    $html = BBCode($bb_body);
    //BBCode it.
    $subject = preg_replace("/[^\\S ]/ui", '', strip_tags($prefix . ' ' . $subject));
    //"remove everything that's not [non-whitespace or space]"
    //preg_replace("/[^[:alnum][:space]]/ui", '', $string);?
    //Ok everything seems to be working, let's go ahead
    Swift_Preferences::getInstance()->setCacheType('array');
    //Prevents a ton of warnings about SwiftMail's DiskKeyCache, thus actually speeding things up considerably.
    //Connect to the SMTP server
    $transport = Swift_SmtpTransport::newInstance($SMTP_SERVER, $SMTP_SERVER_PORT, $SMTP_SERVER_PROTOCOL)->setUsername($EMAIL_USERNAME)->setPassword($EMAIL_PASSWORD);
    //Make a Mailer that will send through that transport (limiting to 50/send)
    $mailer = Swift_Mailer::newInstance($transport);
    //$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(50, 1));//Max 50 emails per send, 1 sec delay between sends
    try {
        //Mush all info into the Mailer
        $message = Swift_Message::newInstance($subject)->setFrom(array($EMAIL_ADDRESS => 'LHS Math Club Mailbot'))->setBcc($bcc_list)->setContentType("text/html")->setBody($html)->setReplyTo($reply_to);
        foreach ($headers as $field => $value) {
            //Add custom headers, such as listserv stuff.
            $message->getHeaders()->addTextHeader($field, $value);
        }
        //Send the message
        if (!$mailer->send($message)) {
            LOG::fatal('Error sending email');
        }
    } catch (Exception $e) {
        LOG::fatal('Email exception: ' . $e->getMessage());
    }
    return true;
}
예제 #9
0
 /**
  * Account sign in form processing.
  *
  * @return Redirect
  */
 public function login(Request $request)
 {
     $validator = $this->validator(Input::all());
     if ($validator->fails()) {
         return redirect()->back()->withInput()->withErrors($validator);
     }
     // Should we even check for LDAP users?
     if (Setting::getSettings()->ldap_enabled == '1') {
         LOG::debug("LDAP is enabled.");
         // Check if the user exists in the database
         $user = User::where('username', '=', Input::get('username'))->whereNull('deleted_at')->first();
         LOG::debug("Local auth lookup complete");
         try {
             Ldap::findAndBindUserLdap($request->input('username'), $request->input('password'));
             LOG::debug("Binding user to LDAP.");
         } catch (\Exception $e) {
             LOG::debug("User " . Input::get('username') . ' did not authenticate successfully against LDAP.');
             //$ldap_error = $e->getMessage();
             // return redirect()->back()->withInput()->with('error',$e->getMessage());
         }
         // The user does not exist in the database. Try to get them from LDAP.
         // If user does not exist and authenticates sucessfully with LDAP we
         // will create it on the fly and sign in with default permissions
         if (!$user) {
             LOG::debug("Local user " . Input::get('username') . " does not exist");
             try {
                 if ($userattr = Ldap::findAndBindUserLdap($request->input('username'), $request->input('password'))) {
                     LOG::debug("Creating local user " . Input::get('username'));
                     if ($newuser = Ldap::createUserFromLdap($userattr)) {
                         LOG::debug("Local user created..");
                     } else {
                         LOG::debug("Could not create local user.");
                     }
                 } else {
                     LOG::debug("User did not authenticate correctly against LDAP. No local user was created.");
                 }
             } catch (\Exception $e) {
                 return redirect()->back()->withInput()->with('error', $e->getMessage());
             }
             // If the user exists and they were imported from LDAP already
         } else {
             LOG::debug("Local user " . Input::get('username') . " exists in database. Authenticating existing user against LDAP.");
             if ($ldap_user = Ldap::findAndBindUserLdap($request->input('username'), $request->input('password'))) {
                 $ldap_attr = Ldap::parseAndMapLdapAttributes($ldap_user);
                 LOG::debug("Valid LDAP login. Updating the local data.");
                 $user->password = bcrypt($request->input('password'));
                 $user->email = $ldap_attr['email'];
                 $user->first_name = $ldap_attr['firstname'];
                 $user->last_name = $ldap_attr['lastname'];
                 $user->save();
             } else {
                 LOG::debug("User " . Input::get('username') . " did not authenticate correctly against LDAP. Local user was not updated.");
             }
             // End LDAP auth
         }
         // End if(!user)
         // NO LDAP enabled - just try to login the user normally
     }
     LOG::debug("Authenticating user against database.");
     // Try to log the user in
     if (!Auth::attempt(Input::only('username', 'password'), Input::get('remember-me', 0))) {
         LOG::debug("Local authentication failed.");
         // throw new Cartalyst\Sentry\Users\UserNotFoundException();
         return redirect()->back()->withInput()->with('error', trans('auth/message.account_not_found'));
     }
     // Get the page we were before
     $redirect = \Session::get('loginRedirect', 'home');
     // Unset the page we were before from the session
     \Session::forget('loginRedirect');
     // Redirect to the users page
     return redirect()->to($redirect)->with('success', trans('auth/message.signin.success'));
     // Ooops.. something went wrong
     return redirect()->back()->withInput()->withErrors($this->messageBag);
 }
예제 #10
0
function logWarn($msg)
{
    LOG::write($msg, 'WARN');
}
예제 #11
0
 /**
  * Will set the path to the KRUMO variable dumper. The KRUMO is an external plugin with it's own JS, that we use to dump system
  * variables globally defined in a recursive manner, which allows a developer the content of variables when the error happened. In
  * the development stage of a project, this advantage helps the developer debug faster and after fixing the problem, to concentrate
  * more on the features he has to do, rather than on what to use and how to debug ...
  *
  * @param FilePath $pathToKrumo Set the path to the KRUMO plugin
  * @return B Will return true if the path was set
  * @author Catalin Z. Alexandru <*****@*****.**>
  * @copyright Under the terms of the GNU General Public License v3
  * @version $Id: 02_LOG.php 313 2009-10-09 13:27:52Z catalin.zamfir $
  * @since Version 1.0
  * @access protected
  * @static
  * @final
  */
 protected static final function setRAKrumoPath(FilePath $pathToKrumo)
 {
     // Just set the INTERNAL objKrumoObjectDumbper;
     if (self::$objKrumoObjectDumper = $pathToKrumo) {
         // Do return ...
         return new B(TRUE);
     } else {
         // Do return ...
         return new B(FALSE);
     }
 }
예제 #12
0
파일: filters.php 프로젝트: rurix2/snipe-it
        return Redirect::route('signin');
    }
    // Check if the user has access to the admin pages
    if (!Sentry::getUser()->hasAccess('reports')) {
        LOG::debug('Unsufficient permissions');
        // Show the insufficient permissions page
        return Redirect::route('profile')->with("error", "You do not have permission to view this page.");
    }
});
Route::filter('backup-auth', function () {
    if (!Sentry::getUser()->isSuperUser()) {
        LOG::debug('Not a super admin');
        return Redirect::route('home')->with('error', Lang::get('general.insufficient_permissions'));
    }
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function () {
    if (Session::token() != Input::get('_token')) {
        LOG::debug('No CSRF token');
        throw new Illuminate\Session\TokenMismatchException();
    }
});
예제 #13
0
 public function query($sql)
 {
     LOG::ass($sql);
     return $this->db->query($sql);
 }
예제 #14
0
 public static function start($flogname = 'log.txt')
 {
     self::$fplog = fopen($flogname, 'ab');
 }
예제 #15
0
 /**
  * Account sign in form processing.
  *
  * @return Redirect
  */
 public function postSignin()
 {
     // Declare the rules for the form validation
     $rules = array('username' => 'required', 'password' => 'required');
     // Create a new validator instance from our validation rules
     $validator = Validator::make(Input::all(), $rules);
     // If validation fails, we'll exit the operation now.
     if ($validator->fails()) {
         // Ooops.. something went wrong
         return Redirect::back()->withInput()->withErrors($validator);
     }
     try {
         /**
          * =================================================================
          * Hack in LDAP authentication
          */
         // Try to get the user from the database.
         $user = (array) DB::table('users')->where('username', Input::get('username'))->first();
         if ($user && strpos($user["notes"], 'LDAP') !== false) {
             LOG::debug("Authenticating user against LDAP.");
             if ($this->ldap(Input::get('username'), Input::get('password'))) {
                 LOG::debug("valid login");
                 $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
                 $user = Sentry::findUserByLogin(Input::get('username'));
                 $user->password = $pass;
                 $user->save();
                 $credentials = array('username' => Input::get('username'), 'password' => $pass);
                 Sentry::authenticate($credentials, Input::get('remember-me', 0));
             } else {
                 throw new Cartalyst\Sentry\Users\UserNotFoundException();
             }
         } else {
             LOG::debug("Authenticating user against database.");
             // Try to log the user in
             Sentry::authenticate(Input::only('username', 'password'), Input::get('remember-me', 0));
         }
         // Get the page we were before
         $redirect = Session::get('loginRedirect', 'account');
         // Unset the page we were before from the session
         Session::forget('loginRedirect');
         // Redirect to the users page
         return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
     } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
         $this->messageBag->add('username', Lang::get('auth/message.account_not_found'));
     } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
         $this->messageBag->add('username', Lang::get('auth/message.account_not_activated'));
     } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
         $this->messageBag->add('username', Lang::get('auth/message.account_suspended'));
     } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {
         $this->messageBag->add('username', Lang::get('auth/message.account_banned'));
     }
     // Ooops.. something went wrong
     return Redirect::back()->withInput()->withErrors($this->messageBag);
 }
예제 #16
0
 public function doBind()
 {
     $bindCode = text($_POST['bindCode']);
     $bind_name = text($_POST['bind_name']);
     $bindid = session("temp_bindid");
     if (empty($bindid)) {
         ajaxmsg('请先发送短信验证码!', 0);
     }
     $bindid = intval($bindid);
     if (session("temp_bindusername") != $bind_name) {
         ajaxmsg('您已经修改绑定账号,请重新发送短信校验码!', 0);
     }
     if (is_verify($this->uid, $bindCode, 8, 10 * 60)) {
         LOG::write("bindid:" . $bindid . ",uid:" . $this->uid, Log::DEBUG);
         M("members")->where(array("id" => $this->uid))->save(array("bind_uid" => $bindid));
         session("temp_bindid", null);
         session("temp_bindusername", null);
         ajaxmsg('绑定成功!');
     } else {
         ajaxmsg('短信校验码不正确!!', 0);
     }
 }
예제 #17
0
	public function massSend($mob,$content,$time)
	{
	
		$http = 'http://119.145.9.12/sendSMS.action';
		$content = str_replace("@", "", $content);
		$data = array
		(
				'enterpriseID'=>"15621",
				'loginName'=>"admin",
				'password'=>strtolower(md5("ytt131021")),
				'smsId'=>"",
				'subPort'=>"",
				'Phone'=>"",
				'mobiles'=>$mob,
				'content'=>$content,
				'sendTime'=>$time
		);
		$ret = $this->do_post($http, $data);
		$xml = simplexml_load_string($ret);
		if($xml->Result != 0){
			LOG::write(dump($xml, false, null, false));
		}
		return $xml;
	}
예제 #18
0
 /**
  *在脚本结束处调用获取脚本结束时间的微秒值
  */
 static function stop()
 {
     self::$stopTime = microtime(true);
     //将获取的时间赋给成员属性$stopTime
 }
예제 #19
0
파일: mom.php 프로젝트: r67/masomatic
 public static function delete($name, $array)
 {
     $sql = "delete FROM " . $name;
     if ($array) {
         $first = true;
         $sql .= " where ";
         foreach ($array as $key => $value) {
             if (!$first) {
                 $sql = " and ";
             } else {
                 $first = false;
             }
             $sql .= $key . "='" . $value . "' ";
         }
     }
     LOG::trace("sql:{$sql}");
     $ds = new DataSource();
     $result = $ds->query($sql);
     if (!is_numeric($result)) {
         if ($ds->error()) {
             throw new Exception($ds->error());
         }
     }
     return $result;
 }
예제 #20
0
파일: Ldap.php 프로젝트: jbirdkerr/snipe-it
 /**
  * Create user from LDAP attributes
  *
  * @author [A. Gianotto] [<*****@*****.**>]
  * @since [v3.0]
  * @param $ldapatttibutes
  * @return array|bool
  */
 static function createUserFromLdap($ldapatttibutes)
 {
     $item = Ldap::parseAndMapLdapAttributes($ldapatttibutes);
     // Create user from LDAP data
     if (!empty($item["username"])) {
         $user = new User();
         $user->first_name = $item["firstname"];
         $user->last_name = $item["lastname"];
         $user->username = $item["username"];
         $user->email = $item["email"];
         if (Setting::getSettings()->ldap_pw_sync == '1') {
             $user->password = bcrypt(Input::get("password"));
         } else {
             $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 25);
             $user->password = bcrypt($pass);
         }
         $user->activated = 1;
         $user->ldap_import = 1;
         $user->notes = 'Imported on first login from LDAP';
         if ($user->save()) {
             return true;
         } else {
             LOG::debug('Could not create user.' . $user->getErrors());
             exit;
         }
     }
     return false;
 }
예제 #21
0
 /**
  * @brief 返回经过缩放后的图片数据
  *
  * reference: http://php.net/manual/zh/function.imagejpeg.php
  */
 public static function scaleImageFileToBlob($param)
 {
     $source_pic = $param['path'];
     $max_width = $param['width'];
     $max_height = $param['height'];
     list($width, $height, $image_type) = getimagesize($source_pic);
     switch ($image_type) {
         case 1:
             $src = imagecreatefromgif($source_pic);
             break;
         case 2:
             $src = imagecreatefromjpeg($source_pic);
             break;
         case 3:
             $src = imagecreatefrompng($source_pic);
             break;
         default:
             return '';
             break;
     }
     $x_ratio = $max_width / $width;
     $y_ratio = $max_height / $height;
     if ($width <= $max_width && $height <= $max_height) {
         $tn_width = $width;
         $tn_height = $height;
     } else {
         if ($x_ratio * $height < $max_height) {
             $tn_height = ceil($x_ratio * $height);
             $tn_width = $max_width;
         } else {
             $tn_width = ceil($y_ratio * $width);
             $tn_height = $max_height;
         }
     }
     LOG::debug('tn_width=' . $tn_width);
     LOG::debug('tn_height=' . $tn_width);
     $tmp = imagecreatetruecolor($tn_width, $tn_height);
     /* Check if this image is PNG or GIF, then set if Transparent*/
     if ($image_type == 1 or $image_type == 3) {
         imagealphablending($tmp, false);
         imagesavealpha($tmp, true);
         $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
         imagefilledrectangle($tmp, 0, 0, $tn_width, $tn_height, $transparent);
     }
     imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
     /*
      * imageXXX() only has two options, save as a file, or send to the browser.
      * It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
      * So I start the output buffering, use imageXXX() to output the data stream to the browser, 
      * get the contents of the stream, and use clean to silently discard the buffered contents.
      */
     ob_start();
     switch ($image_type) {
         case 1:
             imagegif($tmp);
             break;
         case 2:
             imagejpeg($tmp, NULL, 75);
             break;
             // best quality
         // best quality
         case 3:
             imagepng($tmp, NULL, 8);
             break;
             // no compression
         // no compression
         default:
             echo '';
             break;
     }
     $final_image = ob_get_contents();
     ob_end_clean();
     return $final_image;
 }
}
// Load config
//$config = parse_ini_file($INIFILE, true,INI_SCANNER_RAW); // INI_SCANNER_RAW works only in php 5.3
$config = parse_ini_file($INIFILE, true);
// Replace DOUBLEQUOTES string with '"'. Can't have '"' in ini file in php <5.3
foreach ($config['main'] as $key => $val) {
    if ($key != 'DQ') {
        $config['main'][$key] = str_replace($config['main']['DQ'], '"', $config['main'][$key]);
    }
}
if ($error = checkConfig($config)) {
    // Check required parameters from config file
    die($error);
}
//var_dump($config);
$log = new LOG($config['main']['log_dir'] . 'restart.log');
// Log object
$ckStart = new CheckStart($config['main']['log_dir'] . 'restart.lock');
if (!$ckStart->canStart()) {
    // Check if script already running. Doesn't allow customer to send multiple restart requests
    printLogAndDie("Script is already running.");
}
//$options = getopt('',array ('user:'******'pass:'******'status:'));	// Read input Works in php 5.3 and above
//var_dump($options);
foreach ($argv as $v) {
    // Read input works in php < 5.3
    if (false !== strpos($v, '=')) {
        $parts = explode('=', $v);
        if (strpos($parts[0], '--') === 0) {
            $options[substr($parts[0], 2)] = $parts[1];
        }
예제 #23
0
파일: Ldap.php 프로젝트: dmeltzer/snipe-it
 /**
  * Create user from LDAP attributes
  *
  * @author [A. Gianotto] [<*****@*****.**>]
  * @since [v3.0]
  * @param $ldapatttibutes
  * @return array|bool
  */
 static function createUserFromLdap($ldapatttibutes)
 {
     $item = Ldap::parseAndMapLdapAttributes($ldapatttibutes);
     // Create user from LDAP data
     if (!empty($item["username"])) {
         $user = new User();
         $user->first_name = $item["firstname"];
         $user->last_name = $item["lastname"];
         $user->username = $item["username"];
         $user->email = $item["email"];
         $user->password = bcrypt(Input::get("password"));
         $user->activated = 1;
         $user->ldap_import = 1;
         $user->notes = 'Imported on first login from LDAP';
         if ($user->save()) {
             return true;
         } else {
             LOG::debug('Could not create user.' . $user->getErrors());
             exit;
         }
     }
     return false;
 }
예제 #24
0
// Action we need to do
// Start here
set_error_handler("error_handler", E_ALL);
// Catch all error/notice messages
if (!file_exists($INIFILE)) {
    // Check if config file exists
    showPage($action, "Config file not found", "");
}
// Load config
$config = parse_ini_file($INIFILE, true);
if ($error = checkConfig($config)) {
    // Check required parameters from config file
    showPage($action, $error, "");
}
$ckStart = new CheckStart($config['main']['log_dir'] . 'index.lock');
$log = new LOG($config['main']['log_dir'] . 'index.log');
$action = array_key_exists('act', $_REQUEST) ? $_REQUEST['act'] : '';
// Action
if ($action == 'checksum') {
    // Calculate checksum and show it to user
    if (array_key_exists('UserName', $_REQUEST) && array_key_exists('Password', $_REQUEST)) {
        $message = "The checksum is: " . calcCheckSum($_REQUEST['UserName'], $_REQUEST['Password']);
        $action = '';
    }
    showPage($action, $message, "");
} else {
    if ($action == 'status') {
        // Show status page
        if (!array_key_exists('id', $_REQUEST) || !preg_match('/^\\d+\\.txt$/', $_REQUEST['id']) || !file_exists($config['main']['stat_dir'] . $_REQUEST['id'])) {
            $message = "Status file not found";
            $action = '';
예제 #25
0
파일: mom-util.php 프로젝트: r67/masomatic
 static function ass($val)
 {
     LOG::trace("value:" . print_r($val, true));
 }
예제 #26
0
 public function checkOutNotifySlack($settings, $admin, $note = null)
 {
     if ($settings->slack_endpoint) {
         $slack_settings = ['username' => $settings->botname, 'channel' => $settings->slack_channel, 'link_names' => true];
         $client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
         try {
             $client->attach(['color' => 'good', 'fields' => [['title' => 'Checked Out:', 'value' => 'HARDWARE asset <' . config('app.url') . '/hardware/' . $this->id . '/view' . '|' . $this->showAssetName() . '> checked out to <' . config('app.url') . '/admin/users/' . $this->assigned_to . '/view|' . $this->assigneduser->fullName() . '> by <' . config('app.url') . '/admin/users/' . Auth::user()->id . '/view' . '|' . $admin->fullName() . '>.'], ['title' => 'Note:', 'value' => e($note)]]])->send('Asset Checked Out');
         } catch (Exception $e) {
             LOG::error($e);
         }
     }
 }
예제 #27
0
 /**
  * Account sign in form processing.
  *
  * @return Redirect
  */
 public function postSignin()
 {
     // Declare the rules for the form validation
     $rules = array('username' => 'required', 'password' => 'required');
     // Create a new validator instance from our validation rules
     $validator = Validator::make(Input::all(), $rules);
     // If validation fails, we'll exit the operation now.
     if ($validator->fails()) {
         // Ooops.. something went wrong
         return Redirect::back()->withInput()->withErrors($validator);
     }
     try {
         // Should we even check for LDAP users?
         if (Setting::getSettings()->ldap_enabled == '1') {
             LOG::debug("LDAP is enabled.");
             // Check if the user exists in the database
             $user = User::where('username', '=', Input::get('username'))->whereNull('deleted_at')->first();
             LOG::debug("Sentry lookup complete");
             // The user does not exist in the database. Try to get them from LDAP.
             // If user does not exist and authenticates sucessfully with LDAP we
             // will create it on the fly and sign in with default permissions
             if (!$user) {
                 LOG::debug("Local user " . Input::get('username') . " does not exist");
                 if ($userattr = $this->ldap(Input::get('username'), Input::get('password'), true)) {
                     LOG::debug("Creating local user from authenticated LDAP user.");
                     $credentials = $this->createUserFromLdap($userattr);
                 } else {
                     LOG::debug("User did not authenticate correctly against LDAP. No local user was created.");
                 }
                 // If the user exists and they were imported from LDAP already
             } else {
                 LOG::debug("Local user " . Input::get('username') . " exists in database. Authenticating existing user against LDAP.");
                 if ($this->ldap(Input::get('username'), Input::get('password'))) {
                     LOG::debug("Valid LDAP login. Updating the local data.");
                     $sentryuser = Sentry::findUserById($user->id);
                     //need the Sentry object, not the Eloquent object, to access critical password hashing functions
                     $sentryuser->password = Input::get('password');
                     $sentryuser->save();
                 } else {
                     LOG::debug("User did not authenticate correctly against LDAP. Local user was not updated.");
                 }
                 // End LDAP auth
             }
             // End if(!user)
             // NO LDAP enabled - just try to login the user normally
         }
         LOG::debug("Authenticating user against database.");
         // Try to log the user in
         if (!Sentry::authenticate(Input::only('username', 'password'), Input::get('remember-me', 0))) {
             LOG::debug("Local authentication failed.");
             throw new Cartalyst\Sentry\Users\UserNotFoundException();
         }
         // Get the page we were before
         $redirect = Session::get('loginRedirect', 'account');
         // Unset the page we were before from the session
         Session::forget('loginRedirect');
         // Redirect to the users page
         return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
     } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
         LOG::debug("Local authentication: User " . Input::get('username') . " not found");
         $this->messageBag->add('username', Lang::get('auth/message.account_not_found'));
     } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) {
         LOG::debug("Local authentication: Password for " . Input::get('username') . " is incorrect.");
         $this->messageBag->add('username', Lang::get('auth/message.account_not_found'));
     } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
         LOG::debug("Local authentication: User not activated");
         $this->messageBag->add('username', Lang::get('auth/message.account_not_activated'));
     } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
         LOG::debug("Local authentication: Account suspended");
         $this->messageBag->add('username', Lang::get('auth/message.account_suspended'));
     } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {
         LOG::debug("Local authentication: Account banned.");
         $this->messageBag->add('username', Lang::get('auth/message.account_banned'));
     }
     // Ooops.. something went wrong
     return Redirect::back()->withInput()->withErrors($this->messageBag);
 }