yova 3 years ago
parent b3a6d5bef3
commit c02f3b05da

@ -5,9 +5,9 @@ baseURL = "https://wntr.org"
theme = 'hugo-bearblog'
# Basic metadata configuration for your blog.
title = "yova wntr"
author = "Johannes Valentin Winter"
copyright = "Copyright © 2021, Johannes Winter."
title = "yvwntr"
author = "yova"
copyright = "Copyright © 2021, yova"
languageCode = "de-de"
# Generate a nice robots.txt for SEO
@ -22,7 +22,7 @@ ignoreErrors = ["error-disable-taxonomy"]
[params]
# The "description" of your website. This is used in the meta data of your generated html.
description = "Hugo + Bear = :heart:"
description = "Personal website yova yvwntr"
# The path to your "favicon". This should be a square (at least 32px x 32px) png-file.
# Hint: It's good practise to also put a "favicon.ico"-file into your "static"-folder.

@ -1,21 +1,2 @@
# A match made in heaven
There is a website obesity crisis. Bloated websites full of scripts, ads, and trackers are slowing your readers down every time they try to read your well-crafted content.
Hugo Bear Blog is all you need to build a fantastic and optimized site or blog. It works perfectly on **any** viewing device. All you need to focus on is writing good content.
[Go to the original bear blog](https://bearblog.dev/).
---
What happens when you combine the worlds' fastest, most lightweight static site generator with a design theme built to provide you with free, no-nonsense, super-fast blogging capabilities?
**Use this theme, and find out!**
Made with 💟 by [Jan Raasch](https://www.janraasch.com).
---
Simply publish content online, grow an audience, and keep your pages tiny, fast, and **optimized for search engines**.
Each page is ~5kb, and you can **host your blog yourself**.
Free thoughts for free minds.
Free software for a free society.

@ -1,18 +0,0 @@
+++
title = "Bear"
menu = "main"
+++
# Bear
Website: https://bearblog.dev
There is a website obesity crisis. Bloated websites are full of scripts, ads, and trackers slowing your readers down every time they try to read your well-crafted content.
Bear is all you need to build a fantastic and optimized site or blog. It works perfectly on **any** viewing device. All you need to focus on is writing good content.
Bear makes it simple to publish content online and grow an audience while keeping pages tiny, fast, and **optimized for search engines.**
Each page is ~5kb.
Learn more and contribute on [GitHub](https://github.com/HermanMartinus/bearblog).

@ -0,0 +1,5 @@
+++
title = "Contact"
menu = "main"
+++
[Contact me]({{< siteurl >}}/contact-form/formpage.html)

@ -1,26 +0,0 @@
+++
title = "Hugo"
menu = "main"
+++
# Hugo
Website: https://gohugo.io
Written in Go, Hugo is an open-source static site generator available under the [Apache Licence 2.0.](https://github.com/gohugoio/hugo/blob/master/LICENSE) Hugo supports TOML, YAML, and JSON data file types, Markdown and HTML content files, and uses shortcodes to add rich content. Other notable features are taxonomies, multilingual mode, image processing, custom output formats, HTML/CSS/JS minification, and support for Sass SCSS workflows.
Hugo makes use of a variety of open source projects including:
* https://github.com/yuin/goldmark
* https://github.com/alecthomas/chroma
* https://github.com/muesli/smartcrop
* https://github.com/spf13/cobra
* https://github.com/spf13/viper
Hugo is ideal for blogs, corporate websites, creative portfolios, online magazines, single-page applications, or even a website with thousands of pages.
Hugo is for people who want to hand-code their own website without worrying about setting up complicated runtimes, dependencies, and databases.
Websites built with Hugo are swift, secure and can be deployed anywhere including, AWS, GitHub Pages, Heroku, Netlify, and any other hosting provider.
Learn more and contribute on [GitHub](https://github.com/gohugoio).

@ -0,0 +1,15 @@
+++
title = "Past"
menu = "main"
+++
## Present
- I wrote a bachelor thesis about a [Conceptual model of Solawi](https://cld.freedomhost.de/index.php/s/FJF4iLFWFYbXrCB)
- This led the foundation for growing interest in [valueflo.ws](https://valueflo.ws/).
- I wrote the [Solid Base app](https://lab.allmende.io/solidbase/solidbase) meanwhile.
- I coordinated the [Solid Base project](https://urgenci.net/?s=solidbase) for the german [CSA Network](https://www.solidarische-landwirtschaft.org/das-netzwerk/projekte/solid-base).
- I used to work with [ecobytes](https://ecobytes.net).
## Past

@ -0,0 +1 @@
{{ .Page.Site.BaseURL }}

File diff suppressed because one or more lines are too long

@ -1 +1 @@
{"Target":"sass/style.min.ac3b29eee9e254302a04aca44260f19f19da7d1d3a16e2dbb3e8a152ad617046.css","MediaType":"text/css","Data":{"Integrity":"sha256-rDsp7uniVDAqBKykQmDxnxnafR06FuLbs+ihUq1hcEY="}}
{"Target":"sass/style.min.eabe1aa4bd266a15f7b39b122bd6a5cc75cb067e5373631ac21d7815d6240d6f.css","MediaType":"text/css","Data":{"Integrity":"sha256-6r4apL0mahX3s5sSK9alzHXLBn5Tc2Mawh14FdYkDW8="}}

@ -0,0 +1,19 @@
Copyright (c) 2017 Prasanth Janardanan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,43 @@
html
{
height:100%;
width:100%;
}
body{
background:url('images/jurassic-coast-1089035_1920.jpg') no-repeat;
background-size: cover;
height:100%;
}
.form-top{
margin-top: 30px;
}
.panel{
box-shadow: 0 1px 6px 0 rgba(0,0,0,.12), 0 1px 6px 0 rgba(0,0,0,.12);
border-radius: 6px;
border: 0;
}
@-moz-document url-prefix() {
.form-control{
height: auto;
}
}
.panel-primary{
background-color: #2c3e50;
color: #fff;
}
.panel-primary>.panel-heading {
color: #fff;
font-size: 20px;
background-color: #2c3e50;
border-color: #2c3e50;
}
.btn-warning{
background-color: transparent;
border-color: #bdc3c7;
}

@ -0,0 +1,63 @@
$(function()
{
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
$.ajax({
type: "POST",
url: 'handler.php',
data: $form.serialize(),
success: after_form_submitted,
dataType: 'json'
});
});
});

@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>HTML5 Contact Form To Send Email On Form Submission - reusable form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="form.css" >
<script src="form.js"></script>
</head>
<body >
<div class="container">
<!-- Form Started -->
<div class="container form-top">
<div class="row">
<div class="col-md-6 col-md-offset-3 col-sm-12 col-xs-12">
<div class="panel panel-danger">
<div class="panel-body">
<form id="reused_form">
<div class="form-group">
<label><i class="fa fa-user" aria-hidden="true"></i> Name</label>
<input type="text" name="name" class="form-control" placeholder="Enter Name">
</div>
<div class="form-group">
<label><i class="fa fa-envelope" aria-hidden="true"></i> Email</label>
<input type="email" name="email" class="form-control" placeholder="Enter Email">
</div>
<div class="form-group">
<label><i class="fa fa-comment" aria-hidden="true"></i> Message</label>
<textarea rows="3" name="message" class="form-control" placeholder="Type Your Message"></textarea>
</div>
<div class="form-group">
<button class="btn btn-raised btn-block btn-danger">Post &rarr;</button>
</div>
</form>
<div id="error_message" style="width:100%; height:100%; display:none; ">
<h4>
Error
</h4>
Sorry there was an error sending your form.
</div>
<div id="success_message" style="width:100%; height:100%; display:none; ">
<h2>Success! Your Message was Sent Successfully.</h2>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Form Ended -->
</div>
</body>
</html>

@ -0,0 +1,26 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
Tested working with PHP5.4 and above (including PHP 7 )
*/
require_once './vendor/autoload.php';
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['name','email'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('comments')->maxLength(6000);
$pp->sendEmailTo('someone@gmail.com'); // ← Your email here
echo $pp->process($_POST);

Binary file not shown.

After

Width:  |  Height:  |  Size: 802 KiB

@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reusable Form Readme First</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<h1>ReusableForms - Readme</h1>
<h2>Requirements</h2>
The server side script is in PHP. So you should have a working PHP setup on the webserver.
<p>
The script is tested working with PHP 5.4 and above (including PHP 7 )
</p>
<h2>Usage</h2>
<ol>
<li>Open the file named "handler.php" <br/> Look for <code>sendEmailTo</code> add the email addresses to receive the form submissions.</li>
<li>Upload this <strong>whole folder</strong> to your website</li>
<li>Open the formpage.html in your browser and test</li>
</ol>
Once you have the form working you can tweak it to your needs. Feel free to edit the form.css or form.js files to customize and make it work better for you.
<p>
See a <a href="https://youtu.be/jAr4ZtLnmn0">video demo here</a>
</p>
<h2>Customizations</h2>
Read the <a href="http://reusableforms.com/doc/customization">customization guide</a> for help on customizing the form.
<h2>Updates</h2>
For updates, visit: <a href="http://reusableforms.com">ReusableForms.com</a>
<h2>Contact</h2>
Please report bugs or issues here:
<a href="http://reusableforms.com/contact">http://reusableforms.com/contact</a>
<p></p>
<hr/>
<p class="help-block">
This form was downloaded from:<br/>
<a href="http://reusableforms.com/d/o5/html5-contact-form-send-email">HTML5 Contact Form To Send Email On Form Submission</a>
</p>
</div>
</div>
</div>
</body>
</html>

@ -0,0 +1,269 @@
<?php
namespace FormGuide\Handlx;
use FormGuide\PHPFormValidator\FormValidator;
use PHPMailer;
use FormGuide\Handlx\Microtemplate;
use Gregwar\Captcha\CaptchaBuilder;
/**
* FormHandler
* A wrapper class that handles common form handling tasks
* - handles Form validations using PHPFormValidator class
* - sends email using PHPMailer
* - can handle captcha validation
* - can handle file uploads and attaching the upload to email
*
* ==== Sample usage ====
* $fh = FormHandler::create()->validate(function($validator)
* {
* $validator->fields(['name','email'])
* ->areRequired()->maxLength(50);
* $validator->field('email')->isEmail();
*
* })->useMailTemplate(__DIR__.'/templ/email.php')
* ->sendEmailTo('you@website.com');
*
* $fh->process($_POST);
*/
class FormHandler
{
private $emails;
public $validator;
private $mailer;
private $mail_template;
private $captcha;
private $attachments;
private $recaptcha;
public function __construct()
{
$this->emails = array();
$this->validator = FormValidator::create();
$this->mailer = new PHPMailer;
$this->mail_template='';
$this->mailer->Subject = "Contact Form Submission ";
$host = isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost';
$from_email ='forms@'.$host;
$this->mailer->setFrom($from_email,'Contact Form',false);
$this->captcha = false;
$this->attachments = [];
$this->recaptcha =null;
}
/**
* sendEmailTo: add a recipient email address
* @param string/array $email_s one or more emails. If more than one emails, pass the emails as array
* @return The form handler object itself so that the methods can be chained
*/
public function sendEmailTo($email_s)
{
if(is_array($email_s))
{
$this->emails =array_merge($this->emails, $email_s);
}
else
{
$this->emails[] = $email_s;
}
return $this;
}
public function useMailTemplate($templ_path)
{
$this->mail_template = $templ_path;
return $this;
}
/**
* [attachFiles find the file uplods and attach to the email]
* @param array $fields The array of field names
*/
public function attachFiles($fields)
{
$this->attachments = array_merge($this->attachments, $fields);
return $this;
}
public function getRecipients()
{
return $this->emails;
}
/**
* [validate add Validations. This function takes a call back function which receives the PHPFormValidator object]
* @param function $validator_fn The funtion gets a validator parameter using which, you can add validations
*/
public function validate($validator_fn)
{
$validator_fn($this->validator);
return $this;
}
public function requireReCaptcha($config_fn=null)
{
$this->recaptcha = new ReCaptchaValidator();
$this->recaptcha->enable(true);
if($config_fn)
{
$config_fn($this->recaptcha);
}
return $this;
}
public function getReCaptcha()
{
return $this->recaptcha;
}
public function requireCaptcha($enable=true)
{
$this->captcha = $enable;
return $this;
}
public function getValidator()
{
return $this->validator;
}
public function configMailer($mailconfig_fn)
{
$mailconfig_fn($this->mailer);
return $this;
}
public function getMailer()
{
return $this->mailer;
}
public static function create()
{
return new FormHandler();
}
public function process($post_data)
{
if($this->captcha === true)
{
$res = $this->validate_captcha($post_data);
if($res !== true)
{
return $res;
}
}
if($this->recaptcha !== null &&
$this->recaptcha->isEnabled())
{
if($this->recaptcha->validate() !== true)
{
return json_encode([
'result'=>'recaptcha_validation_failed',
'errors'=>['captcha'=>'ReCaptcha Validation Failed.']
]);
}
}
$this->validator->test($post_data);
//if(false == $this->validator->test($post_data))
if($this->validator->hasErrors())
{
return json_encode([
'result'=>'validation_failed',
'errors'=>$this->validator->getErrors(/*associative*/ true)
]);
}
if(!empty($this->emails))
{
foreach($this->emails as $email)
{
$this->mailer->addAddress($email);
}
$this->compose_mail($post_data);
if(!empty($this->attachments))
{
$this->attach_files();
}
if(!$this->mailer->send())
{
return json_encode([
'result'=>'error_sending_email',
'errors'=> ['mail'=> $this->mailer->ErrorInfo]
]);
}
}
return json_encode(['result'=>'success']);
}
private function validate_captcha($post)
{
@session_start();
if(empty($post['captcha']))
{
return json_encode([
'result'=>'captcha_error',
'errors'=>['captcha'=>'Captcha code not entered']
]);
}
else
{
$usercaptcha = trim($post['captcha']);
if($_SESSION['user_phrase'] !== $usercaptcha)
{
return json_encode([
'result'=>'captcha_error',
'errors'=>['captcha'=>'Captcha code does not match']
]);
}
}
return true;
}
private function attach_files()
{
foreach($this->attachments as $file_field)
{
if (!array_key_exists($file_field, $_FILES))
{
continue;
}
$filename = $_FILES[$file_field]['name'];
$uploadfile = tempnam(sys_get_temp_dir(), sha1($filename));
if (!move_uploaded_file($_FILES[$file_field]['tmp_name'],
$uploadfile))
{
continue;
}
$this->mailer->addAttachment($uploadfile, $filename);
}
}
private function compose_mail($post)
{
$content = "Form submission: \n\n";
foreach($post as $name=>$value)
{
$content .= ucwords($name).":\n";
$content .= "$value\n\n";
}
$this->mailer->Body = $content;
}
}

@ -0,0 +1,50 @@
<?php
namespace FormGuide\Handlx;
class ReCaptchaValidator
{
private $enabled;
private $secret;
public function __construct()
{
$this->enabled=false;
}
public function isEnabled()
{
return $this->enabled;
}
public function enable($enable)
{
$this->enabled = $enable;
}
public function initSecretKey($key)
{
$this->secret = $key;
}
public function validate()
{
if(empty($_POST['g-recaptcha-response']))
{
return false;
}
$captcha=$_POST['g-recaptcha-response'];
$url =
'https://www.google.com/recaptcha/api/siteverify?secret='.$this->secret.'&response='.$captcha.'&remoteip='.$_SERVER['REMOTE_ADDR'];
$resp_raw = file_get_contents($url);
$response=json_decode($resp_raw, true);
if(!empty($response['success']) && $response['success'])
{
return true;
}
return false;
}
}

@ -0,0 +1,4 @@
<?php
require_once '../vendor/autoload.php';
require_once 'FormHandler.php';

@ -0,0 +1,4 @@
composer.phar
/vendor/
composer.lock
.DS_Store

@ -0,0 +1,19 @@
Copyright (c) 2017 Prasanth Janardhanan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,49 @@
# PHPFormValidator
A PHP Library for 'self-documenting' server side Form Validations.
A typical usage would be like this:
```php
use FormGuide\PHPFormValidator\FormValidator;
$validator = FormValidator::create();
$validator->fields(['name','email'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
if(!$validator->test($_POST))
{
return json_encode($validator->getErrors(true));
}
```
## Installation using composer
```
composer require FormGuide/PHPFormValidator
```
## Declaring validations for single fields
```php
$validator->field('email')->isEmail()->isRequired();
```
## Declaring validations for multiple fields
```php
$validator->fields(['name','email'])->areRequired()->maxLength(50);
```
This is equivalent to:
```php
$validator->field('name')->isRequired()->maxLength(50);
$validator->field('email')->isRequired()->maxLength(50);
```

@ -0,0 +1,22 @@
{
"name": "FormGuide/PHPFormValidator",
"description": "A PHP Library for Self-Documenting Form Validations",
"license": "MIT",
"keywords": ["form validation", "php form validation"],
"authors": [
{
"name": "Prasanth Janardhanan"
}
],
"require": {
"php": ">=5.4.3"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
},
"autoload": {
"psr-4": {
"FormGuide\\PHPFormValidator\\": "src"
}
}
}

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./tests/TestHelper.php"
backupGlobals="false"
backupStaticAttributes="false"
strict="true"
colors="true"
verbose="true">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

@ -0,0 +1,78 @@
<?php
namespace FormGuide\PHPFormValidator;
class FieldValidator
{
private $field_name;
private $validations;
private $validator;
public function __construct($field_name)
{
$this->field_name = $field_name;
$this->validations = array();
$this->validator = Validators::create($field_name);
$this->validator_map = include('ValidatorMap.php');
}
public function __call($function, $arguments)
{
if(isset($this->validator_map[$function]))
{
return $this->initValidator($function, $arguments);
}
else
{
trigger_error('Call to undefined method '.__CLASS__.'::'.$function.'()', E_USER_ERROR);
}
}
public function initValidator($function, $arguments)
{
$validator_type = $this->validator_map[$function];
$message = null;
$constraint = null;
foreach($arguments as $arg)
{
if(is_array($arg))
{
if(isset($arg['message']))
{
$message = $arg['message'];
}
}
elseif(empty($constraint))
{
$constraint = $arg;
}
}
$this->validations[$validator_type] =
array('value'=>$constraint,'message'=>$message );
return $this;
}
public function test($post)
{
foreach($this->validations as $rule => $details)
{
$this->validator->$rule($post,$details);
}
}
public function hasErrors()
{
return $this->validator->hasErrors();
}
public function getError()
{
return $this->validator->getError();
}
}

@ -0,0 +1,34 @@
<?php
namespace FormGuide\PHPFormValidator;
class FieldValidatorCollection
{
public $fields;
private $validator;
public function __construct()
{
$this->fields = array();
$this->validator_map = include('ValidatorMap.php');
}
public function __call($function, $arguments)
{
if(isset($this->validator_map[$function]))
{
foreach($this->fields as $field)
{
$field->initValidator($function, $arguments);
}
return $this;
}
else
{
trigger_error('Call to undefined method '.__CLASS__.'::'.$name.'()', E_USER_ERROR);
}
}
}

@ -0,0 +1,85 @@
<?php
namespace FormGuide\PHPFormValidator;
class FormValidator
{
private $fields;
public function __construct()
{
$this->fields = array();
}
public static function create()
{
return new FormValidator();
}
public function field($field_name)
{
if(isset($this->fields[$field_name]))
{
return $this->fields[$field_name];
}
$field = new FieldValidator($field_name);
$this->fields[$field_name] = $field;
return $field;
}
public function fields($arr_fields)
{
$coll = new FieldValidatorCollection();
foreach($arr_fields as $field)
{
$coll->fields[] = $this->field($field);
}
return $coll;
}
public function test($post)
{
foreach($this->fields as $field_name => $rule)
{
$rule->test($post);
}
return $this->hasErrors()?false:true;
}
public function hasErrors()
{
foreach($this->fields as $rule)
{
if($rule->hasErrors())
{
return true;
}
}
return false;
}
public function getErrors($associative = false)
{
$errors = array();
foreach($this->fields as $field_name => $field)
{
$error = $field->getError();
if(!empty($error))
{
$errors[$field_name] = $error;
}
}
if(false == $associative)
{
return array_values($errors);
}
return $errors;
}
}

@ -0,0 +1,19 @@
<?php
return
[
'isRequired'=>'required',
'areRequired'=>'required',
'isEmail'=>'email',
'areEmails'=>'email',
'maxLength'=>'maxlen',
'maxLen'=>'maxlen',
'minLength'=>'minlen',
'minLen'=>'minlen',
'isAlphabetic'=>'alphabetic',
'areAlphabetic'=>'alphabetic',
'Alphabetic'=>'alphabetic',
'isAlphaNumeric'=>'alphanumeric',
'areAlphaNumeric'=>'alphanumeric',
'AlphaNumeric'=>'alphanumeric'
];

@ -0,0 +1,165 @@
<?php
namespace FormGuide\PHPFormValidator;
class Validators
{
private $field_name;
private $errors;
private $validators_list;
public function __construct($field_name)
{
$this->field_name = $field_name;
$this->errors = array();
$this->validators_list = include('ValidatorsList.php');
}
public static function create($field_name)
{
return new Validators($field_name);
}
public function required($post, $details=array())
{
if(empty($post[$this->field_name]))
{
$this->addError("{$this->field_name} is Required.");
return false;
}
$value = trim($post[$this->field_name]);
if(empty($value))
{
$this->addError("{$this->field_name} is Required.");
return false;
}
return true;
}
public function __call($function, $arguments)
{
//if(in_array('email', $this->validator_names,TRUE))
if(isset($this->validators_list[$function]))
{
$post = $arguments[0];
$details = $arguments[1];
return $this->testField($function, $post, $details);
}
else
{
trigger_error('Call to undefined method '.__CLASS__.'::'.$function.'()', E_USER_ERROR);
}
}
private function testField($validation, $post, $details)
{
if(empty($post[$this->field_name]))
{
return true;
}
$fn = 'check_'.$validation;
$res = $this->$fn($post, $details);
if(false === $res)
{
$this->validation_error($validation, $details);
}
return $res;
}
private function check_email($post,$details)
{
return (filter_var($post[$this->field_name] , FILTER_VALIDATE_EMAIL) === false)?false:true;
}
private function check_maxlen($post, $details)
{
$maxlen = intval($details['value']);
return (strlen($post[$this->field_name]) <= $maxlen);
}
private function check_minlen($post,$details)
{
$minlen = intval($details['value']);
return (strlen($post[$this->field_name]) >= $minlen);
}
public function check_alphabetic($post,$details)
{
return ctype_alpha($post[$this->field_name]);
}
public function check_alphanumeric($post,$details)
{
return ctype_alnum($post[$this->field_name]);
}
public function check_alphabetic_space($post,$details)
{
$value = str_replace(' ','',$post[$this->field_name]);
return ctype_alpha($value);
}
public function check_alphanumeric_space($post,$details)
{
$value = str_replace(' ','',$post[$this->field_name]);
return ctype_alnum($value);
}
private function validation_error($validation,$details)
{
$error_msg = '';
if(isset($details['message']))
{
$error_msg = $details['message'];
}
elseif(!empty($this->validators_list[$validation]['message']))
{
$error_msg = $this->validators_list[$validation]['message'];
}
$error_msg = $this->interpolate_message($error_msg, $details);
$this->addError($error_msg);
}
private function interpolate_message($message, $details)
{
$constraint = isset($details['value']) ? $details['value']: '';
$replacements = array('%field%' => $this->field_name,
'%constraint%' => $constraint) ;
return strtr($message, $replacements);
}
public function addError($error)
{
$this->errors[] = $error;
}
public function hasErrors()
{
return empty($this->errors)?false:true;
}
public function getErrorCount()
{
return count($this->errors);
}
public function getError()
{
if(empty($this->errors))
{
return null;
}
else
{
return $this->errors[0];
}
}
}

@ -0,0 +1,11 @@
<?php
return
[
'email' => ['message' => '%field% must be a valid email address'],
'maxlen' => ['message' => "%field% length shouldn't exceed %constraint%"],
'minlen' => ['message' => "%field% should have minlength of %constraint%"],
'alphabetic' => ['message' => "%field% shouldn't contain non-alphabetic characters"],
'alphanumeric' => ['message' => "%field% shouldn't contain non-alpha-numeric characters"],
'alphabetic_space' => ['message' => "%field% shouldn't contain non-alphabetic characters"],
'alphanumeric_space' => ['message' => "%field% shouldn't contain non-alpha-numeric characters"],
];

@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitd359baac21f520c04e608f4eed750560::getLoader();

@ -0,0 +1,445 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\';
if (isset($this->prefixDirsPsr4[$search])) {
foreach ($this->prefixDirsPsr4[$search] as $dir) {
$length = $this->prefixLengthsPsr4[$first][$search];
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,17 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'EasyPeasyICS' => $vendorDir . '/phpmailer/phpmailer/extras/EasyPeasyICS.php',
'PHPMailer' => $vendorDir . '/phpmailer/phpmailer/class.phpmailer.php',
'PHPMailerOAuth' => $vendorDir . '/phpmailer/phpmailer/class.phpmaileroauth.php',
'PHPMailerOAuthGoogle' => $vendorDir . '/phpmailer/phpmailer/class.phpmaileroauthgoogle.php',
'POP3' => $vendorDir . '/phpmailer/phpmailer/class.pop3.php',
'SMTP' => $vendorDir . '/phpmailer/phpmailer/class.smtp.php',
'ntlm_sasl_client_class' => $vendorDir . '/phpmailer/phpmailer/extras/ntlm_sasl_client.php',
'phpmailerException' => $vendorDir . '/phpmailer/phpmailer/class.phpmailer.php',
);

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

@ -0,0 +1,12 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Gregwar\\Captcha\\' => array($vendorDir . '/gregwar/captcha'),
'FormGuide\\PHPFormValidator\\' => array($vendorDir . '/FormGuide/PHPFormValidator/src'),
'FormGuide\\Handlx\\' => array($baseDir . '/src'),
);

@ -0,0 +1,52 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitd359baac21f520c04e608f4eed750560
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitd359baac21f520c04e608f4eed750560', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitd359baac21f520c04e608f4eed750560', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitd359baac21f520c04e608f4eed750560::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}

@ -0,0 +1,56 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitd359baac21f520c04e608f4eed750560
{
public static $prefixLengthsPsr4 = array (
'G' =>
array (
'Gregwar\\Captcha\\' => 16,
),
'F' =>
array (
'FormGuide\\PHPFormValidator\\' => 27,
'FormGuide\\Handlx\\' => 17,
),
);
public static $prefixDirsPsr4 = array (
'Gregwar\\Captcha\\' =>
array (
0 => __DIR__ . '/..' . '/gregwar/captcha',
),
'FormGuide\\PHPFormValidator\\' =>
array (
0 => __DIR__ . '/..' . '/FormGuide/PHPFormValidator/src',
),
'FormGuide\\Handlx\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $classMap = array (
'EasyPeasyICS' => __DIR__ . '/..' . '/phpmailer/phpmailer/extras/EasyPeasyICS.php',
'PHPMailer' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.phpmailer.php',
'PHPMailerOAuth' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.phpmaileroauth.php',
'PHPMailerOAuthGoogle' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.phpmaileroauthgoogle.php',
'POP3' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.pop3.php',
'SMTP' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.smtp.php',
'ntlm_sasl_client_class' => __DIR__ . '/..' . '/phpmailer/phpmailer/extras/ntlm_sasl_client.php',
'phpmailerException' => __DIR__ . '/..' . '/phpmailer/phpmailer/class.phpmailer.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitd359baac21f520c04e608f4eed750560::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitd359baac21f520c04e608f4eed750560::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitd359baac21f520c04e608f4eed750560::$classMap;
}, null, ClassLoader::class);
}
}

@ -0,0 +1,178 @@
[
{
"name": "phpmailer/phpmailer",
"version": "v5.2.25",
"version_normalized": "5.2.25.0",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
"reference": "2baf20b01690fba8cf720c1ebcf9b988eda50915"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2baf20b01690fba8cf720c1ebcf9b988eda50915",
"reference": "2baf20b01690fba8cf720c1ebcf9b988eda50915",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"php": ">=5.0.0"
},
"require-dev": {
"doctrine/annotations": "1.2.*",
"jms/serializer": "0.16.*",
"phpdocumentor/phpdocumentor": "2.*",
"phpunit/phpunit": "4.8.*",
"symfony/debug": "2.8.*",
"symfony/filesystem": "2.8.*",
"symfony/translation": "2.8.*",
"symfony/yaml": "2.8.*",
"zendframework/zend-cache": "2.5.1",
"zendframework/zend-config": "2.5.1",
"zendframework/zend-eventmanager": "2.5.1",
"zendframework/zend-filter": "2.5.1",
"zendframework/zend-i18n": "2.5.1",
"zendframework/zend-json": "2.5.1",
"zendframework/zend-math": "2.5.1",
"zendframework/zend-serializer": "2.5.*",
"zendframework/zend-servicemanager": "2.5.*",
"zendframework/zend-stdlib": "2.5.1"
},
"suggest": {
"league/oauth2-google": "Needed for Google XOAUTH2 authentication"
},
"time": "2017-08-28T11:12:07+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"class.phpmailer.php",
"class.phpmaileroauth.php",
"class.phpmaileroauthgoogle.php",
"class.smtp.php",
"class.pop3.php",
"extras/EasyPeasyICS.php",
"extras/ntlm_sasl_client.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1"
],
"authors": [
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Marcus Bointon",
"email": "phpmailer@synchromedia.co.uk"
},
{
"name": "Andy Prevost",
"email": "codeworxtech@users.sourceforge.net"
},
{
"name": "Brent R. Matzelle"
}
],
"description": "PHPMailer is a full-featured email creation and transfer class for PHP"
},
{
"name": "gregwar/captcha",
"version": "v1.1.2",
"version_normalized": "1.1.2.0",
"source": {
"type": "git",
"url": "https://github.com/Gregwar/Captcha.git",
"reference": "2f704c8bc3f1bb5f58994af2729e77ac4e3172e6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Gregwar/Captcha/zipball/2f704c8bc3f1bb5f58994af2729e77ac4e3172e6",
"reference": "2f704c8bc3f1bb5f58994af2729e77ac4e3172e6",
"shasum": ""
},
"require": {
"ext-gd": "*",
"php": ">=5.3.0"
},
"time": "2017-04-19T08:10:55+00:00",
"type": "captcha",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Gregwar\\Captcha\\": "/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Grégoire Passault",
"email": "g.passault@gmail.com",
"homepage": "http://www.gregwar.com/"
},
{
"name": "Jeremy Livingston",
"email": "jeremy.j.livingston@gmail.com"
}
],
"description": "Captcha generator",
"homepage": "https://github.com/Gregwar/Captcha",
"keywords": [
"bot",
"captcha",
"spam"
]
},
{
"name": "FormGuide/PHPFormValidator",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/simfatic/PHPFormValidator.git",
"reference": "51bfb8f0557044f6d3b0d01ffafddf43a393cd18"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/simfatic/PHPFormValidator/zipball/51bfb8f0557044f6d3b0d01ffafddf43a393cd18",
"reference": "51bfb8f0557044f6d3b0d01ffafddf43a393cd18",
"shasum": ""
},
"require": {
"php": ">=5.4.3"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
},
"time": "2017-05-10T08:00:59+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"FormGuide\\PHPFormValidator\\": "src"
}
},
"license": [
"MIT"
],
"authors": [
{
"name": "Prasanth Janardhanan"
}
],
"description": "A PHP Library for Self-Documenting Form Validations",
"keywords": [
"form validation",
"php form validation"
],
"support": {
"source": "https://github.com/simfatic/PHPFormValidator/tree/1.0.1",
"issues": "https://github.com/simfatic/PHPFormValidator/issues"
}
}
]

@ -0,0 +1,3 @@
demo/*.jpg
demo/*.pgm
demo/temp/

@ -0,0 +1,13 @@
language: php
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
script:
- composer install
- phpunit

@ -0,0 +1,720 @@
<?php
namespace Gregwar\Captcha;
use \Exception;
/**
* Builds a new captcha image
* Uses the fingerprint parameter, if one is passed, to generate the same image
*
* @author Gregwar <g.passault@gmail.com>
* @author Jeremy Livingston <jeremy.j.livingston@gmail.com>
*/
class CaptchaBuilder implements CaptchaBuilderInterface
{
/**
* @var array
*/
protected $fingerprint = array();
/**
* @var bool
*/
protected $useFingerprint = false;
/**
* @var array
*/
protected $textColor = null;
/**
* @var array
*/
protected $backgroundColor = null;
/**
* @var array
*/
protected $backgroundImages = array();
/**
* @var resource
*/
protected $contents = null;
/**
* @var string
*/
protected $phrase = null;
/**
* @var PhraseBuilderInterface
*/
protected $builder;
/**
* @var bool
*/
protected $distortion = true;
/**
* The maximum number of lines to draw in front of
* the image. null - use default algorithm
*/
protected $maxFrontLines = null;
/**
* The maximum number of lines to draw behind
* the image. null - use default algorithm
*/
protected $maxBehindLines = null;
/**
* The maximum angle of char
*/
protected $maxAngle = 8;
/**
* The maximum offset of char
*/
protected $maxOffset = 5;
/**
* Is the interpolation enabled ?
*
* @var bool
*/
protected $interpolation = true;
/**
* Ignore all effects
*
* @var bool
*/
protected $ignoreAllEffects = false;
/**
* Allowed image types for the background images
*
* @var array
*/
protected $allowedBackgroundImageTypes = array('image/png', 'image/jpeg', 'image/gif');
/**
* The image contents
*/
public function getContents()
{
return $this->contents;
}
/**
* Enable/Disables the interpolation
*
* @param $interpolate bool True to enable, false to disable
*
* @return CaptchaBuilder
*/
public function setInterpolation($interpolate = true)
{
$this->interpolation = $interpolate;
return $this;
}
/**
* Temporary dir, for OCR check
*/
public $tempDir = 'temp/';
public function __construct($phrase = null, PhraseBuilderInterface $builder = null)
{
if ($builder === null) {
$this->builder = new PhraseBuilder;
} else {
$this->builder = $builder;
}
if ($phrase === null) {
$phrase = $this->builder->build();
}
$this->phrase = $phrase;
}
/**
* Setting the phrase
*/
public function setPhrase($phrase)
{
$this->phrase = (string) $phrase;
}
/**
* Enables/disable distortion
*/
public function setDistortion($distortion)
{
$this->distortion = (bool) $distortion;
return $this;
}
public function setMaxBehindLines($maxBehindLines)
{
$this->maxBehindLines = $maxBehindLines;
return $this;
}
public function setMaxFrontLines($maxFrontLines)
{
$this->maxFrontLines = $maxFrontLines;
return $this;
}
public function setMaxAngle($maxAngle)
{
$this->maxAngle = $maxAngle;
return $this;
}
public function setMaxOffset($maxOffset)
{
$this->maxOffset = $maxOffset;
return $this;
}
/**
* Gets the captcha phrase
*/
public function getPhrase()
{
return $this->phrase;
}
/**
* Returns true if the given phrase is good
*/
public function testPhrase($phrase)
{
return ($this->builder->niceize($phrase) == $this->builder->niceize($this->getPhrase()));
}
/**
* Instantiation
*/
public static function create($phrase = null)
{
return new self($phrase);
}
/**
* Sets the text color to use
*/
public function setTextColor($r, $g, $b)
{
$this->textColor = array($r, $g, $b);
return $this;
}
/**
* Sets the background color to use
*/
public function setBackgroundColor($r, $g, $b)
{
$this->backgroundColor = array($r, $g, $b);
return $this;
}
/**
* Sets the ignoreAllEffects value
*
* @param bool $ignoreAllEffects
* @return CaptchaBuilder
*/
public function setIgnoreAllEffects($ignoreAllEffects)
{
$this->ignoreAllEffects = $ignoreAllEffects;
return $this;
}
/**
* Sets the list of background images to use (one image is randomly selected)
*/
public function setBackgroundImages(array $backgroundImages)
{
$this->backgroundImages = $backgroundImages;
return $this;
}
/**
* Draw lines over the image
*/
protected function drawLine($image, $width, $height, $tcol = null)
{
if ($tcol === null) {
$tcol = imagecolorallocate($image, $this->rand(100, 255), $this->rand(100, 255), $this->rand(100, 255));
}
if ($this->rand(0, 1)) { // Horizontal
$Xa = $this->rand(0, $width/2);
$Ya = $this->rand(0, $height);
$Xb = $this->rand($width/2, $width);
$Yb = $this->rand(0, $height);
} else { // Vertical
$Xa = $this->rand(0, $width);
$Ya = $this->rand(0, $height/2);
$Xb = $this->rand(0, $width);
$Yb = $this->rand($height/2, $height);
}
imagesetthickness($image, $this->rand(1, 3));
imageline($image, $Xa, $Ya, $Xb, $Yb, $tcol);
}
/**
* Apply some post effects
*/
protected function postEffect($image)
{
if (!function_exists('imagefilter')) {
return;
}
if ($this->backgroundColor != null || $this->textColor != null) {
return;
}
// Negate ?
if ($this->rand(0, 1) == 0) {
imagefilter($image, IMG_FILTER_NEGATE);
}
// Edge ?
if ($this->rand(0, 10) == 0) {
imagefilter($image, IMG_FILTER_EDGEDETECT);
}
// Contrast
imagefilter($image, IMG_FILTER_CONTRAST, $this->rand(-50, 10));
// Colorize
if ($this->rand(0, 5) == 0) {
imagefilter($image, IMG_FILTER_COLORIZE, $this->rand(-80, 50), $this->rand(-80, 50), $this->rand(-80, 50));
}
}
/**
* Writes the phrase on the image
*/
protected function writePhrase($image, $phrase, $font, $width, $height)
{
$length = strlen($phrase);
if ($length === 0) {
return \imagecolorallocate($image, 0, 0, 0);
}
// Gets the text size and start position
$size = $width / $length - $this->rand(0, 3) - 1;
$box = \imagettfbbox($size, 0, $font, $phrase);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 + $size;
if (!count($this->textColor)) {
$textColor = array($this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150));
} else {
$textColor = $this->textColor;
}
$col = \imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);
// Write the letters one by one, with random angle
for ($i=0; $i<$length; $i++) {
$box = \imagettfbbox($size, 0, $font, $phrase[$i]);
$w = $box[2] - $box[0];
$angle = $this->rand(-$this->maxAngle, $this->maxAngle);
$offset = $this->rand(-$this->maxOffset, $this->maxOffset);
\imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $phrase[$i]);
$x += $w;
}
return $col;
}
/**
* Try to read the code against an OCR
*/
public function isOCRReadable()
{
if (!is_dir($this->tempDir)) {
@mkdir($this->tempDir, 0755, true);
}
$tempj = $this->tempDir . uniqid('captcha', true) . '.jpg';
$tempp = $this->tempDir . uniqid('captcha', true) . '.pgm';
$this->save($tempj);
shell_exec("convert $tempj $tempp");
$value = trim(strtolower(shell_exec("ocrad $tempp")));
@unlink($tempj);
@unlink($tempp);
return $this->testPhrase($value);
}
/**
* Builds while the code is readable against an OCR
*/
public function buildAgainstOCR($width = 150, $height = 40, $font = null, $fingerprint = null)
{
do {
$this->build($width, $height, $font, $fingerprint);
} while ($this->isOCRReadable());
}
/**
* Generate the image
*/
public function build($width = 150, $height = 40, $font = null, $fingerprint = null)
{
if (null !== $fingerprint) {
$this->fingerprint = $fingerprint;
$this->useFingerprint = true;
} else {
$this->fingerprint = array();
$this->useFingerprint = false;
}
if ($font === null) {
$font = __DIR__ . '/Font/captcha'.$this->rand(0, 5).'.ttf';
}
if (empty($this->backgroundImages)) {
// if background images list is not set, use a color fill as a background
$image = imagecreatetruecolor($width, $height);
if ($this->backgroundColor == null) {
$bg = imagecolorallocate($image, $this->rand(200, 255), $this->rand(200, 255), $this->rand(200, 255));
} else {
$color = $this->backgroundColor;
$bg = imagecolorallocate($image, $color[0], $color[1], $color[2]);
}
$this->background = $bg;
imagefill($image, 0, 0, $bg);
} else {
// use a random background image
$randomBackgroundImage = $this->backgroundImages[rand(0, count($this->backgroundImages)-1)];
$imageType = $this->validateBackgroundImage($randomBackgroundImage);
$image = $this->createBackgroundImageFromType($randomBackgroundImage, $imageType);
}
// Apply effects
if (!$this->ignoreAllEffects) {
$square = $width * $height;
$effects = $this->rand($square/3000, $square/2000);
// set the maximum number of lines to draw in front of the text
if ($this->maxBehindLines != null && $this->maxBehindLines > 0) {
$effects = min($this->maxBehindLines, $effects);
}
if ($this->maxBehindLines !== 0) {
for ($e = 0; $e < $effects; $e++) {
$this->drawLine($image, $width, $height);
}
}
}
// Write CAPTCHA text
$color = $this->writePhrase($image, $this->phrase, $font, $width, $height);
// Apply effects
if (!$this->ignoreAllEffects) {
$square = $width * $height;
$effects = $this->rand($square/3000, $square/2000);
// set the maximum number of lines to draw in front of the text
if ($this->maxFrontLines != null && $this->maxFrontLines > 0) {
$effects = min($this->maxFrontLines, $effects);
}
if ($this->maxFrontLines !== 0) {
for ($e = 0; $e < $effects; $e++) {
$this->drawLine($image, $width, $height, $color);
}
}
}
// Distort the image
if ($this->distortion && !$this->ignoreAllEffects) {
$image = $this->distort($image, $width, $height, $bg);
}
// Post effects
if (!$this->ignoreAllEffects) {
$this->postEffect($image);
}
$this->contents = $image;
return $this;
}
/**
* Distorts the image
*/
public function distort($image, $width, $height, $bg)
{
$contents = imagecreatetruecolor($width, $height);
$X = $this->rand(0, $width);
$Y = $this->rand(0, $height);
$phase = $this->rand(0, 10);
$scale = 1.1 + $this->rand(0, 10000) / 30000;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$Vx = $x - $X;
$Vy = $y - $Y;
$Vn = sqrt($Vx * $Vx + $Vy * $Vy);
if ($Vn != 0) {
$Vn2 = $Vn + 4 * sin($Vn / 30);
$nX = $X + ($Vx * $Vn2 / $Vn);
$nY = $Y + ($Vy * $Vn2 / $Vn);
} else {
$nX = $X;
$nY = $Y;
}
$nY = $nY + $scale * sin($phase + $nX * 0.2);
if ($this->interpolation) {
$p = $this->interpolate(
$nX - floor($nX),
$nY - floor($nY),
$this->getCol($image, floor($nX), floor($nY), $bg),
$this->getCol($image, ceil($nX), floor($nY), $bg),
$this->getCol($image, floor($nX), ceil($nY), $bg),
$this->getCol($image, ceil($nX), ceil($nY), $bg)
);
} else {
$p = $this->getCol($image, round($nX), round($nY), $bg);
}
if ($p == 0) {
$p = $bg;
}
imagesetpixel($contents, $x, $y, $p);
}
}
return $contents;
}
/**
* Saves the Captcha to a jpeg file
*/
public function save($filename, $quality = 90)
{
imagejpeg($this->contents, $filename, $quality);
}
/**
* Gets the image GD
*/
public function getGd()
{
return $this->contents;
}
/**
* Gets the image contents
*/
public function get($quality = 90)
{
ob_start();
$this->output($quality);
return ob_get_clean();
}
/**
* Gets the HTML inline base64
*/
public function inline($quality = 90)
{
return 'data:image/jpeg;base64,' . base64_encode($this->get($quality));
}
/**
* Outputs the image
*/
public function output($quality = 90)
{
imagejpeg($this->contents, null, $quality);
}
/**
* @return array
*/
public function getFingerprint()
{
return $this->fingerprint;
}
/**
* Returns a random number or the next number in the
* fingerprint
*/
protected function rand($min, $max)
{
if (!is_array($this->fingerprint)) {
$this->fingerprint = array();
}
if ($this->useFingerprint) {
$value = current($this->fingerprint);
next($this->fingerprint);
} else {
$value = mt_rand($min, $max);
$this->fingerprint[] = $value;
}
return $value;
}
/**
* @param $x
* @param $y
* @param $nw
* @param $ne
* @param $sw
* @param $se
*
* @return int
*/
protected function interpolate($x, $y, $nw, $ne, $sw, $se)
{
list($r0, $g0, $b0) = $this->getRGB($nw);
list($r1, $g1, $b1) = $this->getRGB($ne);
list($r2, $g2, $b2) = $this->getRGB($sw);
list($r3, $g3, $b3) = $this->getRGB($se);
$cx = 1.0 - $x;
$cy = 1.0 - $y;
$m0 = $cx * $r0 + $x * $r1;
$m1 = $cx * $r2 + $x * $r3;
$r = (int) ($cy * $m0 + $y * $m1);
$m0 = $cx * $g0 + $x * $g1;
$m1 = $cx * $g2 + $x * $g3;
$g = (int) ($cy * $m0 + $y * $m1);
$m0 = $cx * $b0 + $x * $b1;
$m1 = $cx * $b2 + $x * $b3;
$b = (int) ($cy * $m0 + $y * $m1);
return ($r << 16) | ($g << 8) | $b;
}
/**
* @param $image
* @param $x
* @param $y
*
* @return int
*/
protected function getCol($image, $x, $y, $background)
{
$L = imagesx($image);
$H = imagesy($image);
if ($x < 0 || $x >= $L || $y < 0 || $y >= $H) {
return $background;
}
return imagecolorat($image, $x, $y);
}
/**
* @param $col
*
* @return array
*/
protected function getRGB($col)
{
return array(
(int) ($col >> 16) & 0xff,
(int) ($col >> 8) & 0xff,
(int) ($col) & 0xff,
);
}
/**
* Validate the background image path. Return the image type if valid
*
* @param string $backgroundImage
* @return string
* @throws Exception
*/
protected function validateBackgroundImage($backgroundImage)
{
// check if file exists
if (!file_exists($backgroundImage)) {
$backgroundImageExploded = explode('/', $backgroundImage);
$imageFileName = count($backgroundImageExploded) > 1? $backgroundImageExploded[count($backgroundImageExploded)-1] : $backgroundImage;
throw new Exception('Invalid background image: ' . $imageFileName);
}
// check image type
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$imageType = finfo_file($finfo, $backgroundImage);
finfo_close($finfo);
if (!in_array ($imageType, $this->allowedBackgroundImageTypes)) {
throw new Exception('Invalid background image type! Allowed types are: ' . join(', ', $this->allowedBackgroundImageTypes));
}
return $imageType;
}
/**
* Create background image from type
*
* @param string $backgroundImage
* @param string $imageType
* @return resource
* @throws Exception
*/
protected function createBackgroundImageFromType($backgroundImage, $imageType)
{
switch ($imageType) {
case 'image/jpeg':
$image = imagecreatefromjpeg($backgroundImage);
break;
case 'image/png':
$image = imagecreatefrompng($backgroundImage);
break;
case 'image/gif':
$image = imagecreatefromgif($backgroundImage);
break;
default:
throw new Exception('Not supported file type for background image!');
break;
}
return $image;
}
}

@ -0,0 +1,30 @@
<?php
namespace Gregwar\Captcha;
/**
* A Captcha builder
*/
interface CaptchaBuilderInterface
{
/**
* Builds the code
*/
public function build($width, $height, $font, $fingerprint);
/**
* Saves the code to a file
*/
public function save($filename, $quality);
/**
* Gets the image contents
*/
public function get($quality);
/**
* Outputs the image
*/
public function output($quality);
}

@ -0,0 +1,106 @@
<?php
namespace Gregwar\Captcha;
use Symfony\Component\Finder\Finder;
/**
* Handles actions related to captcha image files including saving and garbage collection
*
* @author Gregwar <g.passault@gmail.com>
* @author Jeremy Livingston <jeremy@quizzle.com>
*/
class ImageFileHandler
{
/**
* Name of folder for captcha images
* @var string
*/
protected $imageFolder;
/**
* Absolute path to public web folder
* @var string
*/
protected $webPath;
/**
* Frequency of garbage collection in fractions of 1
* @var int
*/
protected $gcFreq;
/**
* Maximum age of images in minutes
* @var int
*/
protected $expiration;
/**
* @param $imageFolder
* @param $webPath
* @param $gcFreq
* @param $expiration
*/
public function __construct($imageFolder, $webPath, $gcFreq, $expiration)
{
$this->imageFolder = $imageFolder;
$this->webPath = $webPath;
$this->gcFreq = $gcFreq;
$this->expiration = $expiration;
}
/**
* Saves the provided image content as a file
*
* @param string $contents
*
* @return string
*/
public function saveAsFile($contents)
{
$this->createFolderIfMissing();
$filename = md5(uniqid()) . '.jpg';
$filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename;
imagejpeg($contents, $filePath, 15);
return '/' . $this->imageFolder . '/' . $filename;
}
/**
* Randomly runs garbage collection on the image directory
*
* @return bool
*/
public function collectGarbage()
{
if (!mt_rand(1, $this->gcFreq) == 1) {
return false;
}
$this->createFolderIfMissing();
$finder = new Finder();
$criteria = sprintf('<= now - %s minutes', $this->expiration);
$finder->in($this->webPath . '/' . $this->imageFolder)
->date($criteria);
foreach($finder->files() as $file) {
unlink($file->getPathname());
}
return true;
}
/**
* Creates the folder if it doesn't exist
*/
protected function createFolderIfMissing()
{
if (!file_exists($this->webPath . '/' . $this->imageFolder)) {
mkdir($this->webPath . '/' . $this->imageFolder, 0755);
}
}
}

@ -0,0 +1,19 @@
Copyright (c) <2012-2017> Grégoire Passault
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,34 @@
<?php
namespace Gregwar\Captcha;
/**
* Generates random phrase
*
* @author Gregwar <g.passault@gmail.com>
*/
class PhraseBuilder implements PhraseBuilderInterface
{
/**
* Generates random phrase of given length with given charset
*/
public function build($length = 5, $charset = 'abcdefghijklmnpqrstuvwxyz123456789')
{
$phrase = '';
$chars = str_split($charset);
for ($i = 0; $i < $length; $i++) {
$phrase .= $chars[array_rand($chars)];
}
return $phrase;
}
/**
* "Niceize" a code
*/
public function niceize($str)
{
return strtr(strtolower($str), '01', 'ol');
}
}

@ -0,0 +1,21 @@
<?php
namespace Gregwar\Captcha;
/**
* Interface for the PhraseBuilder
*
* @author Gregwar <g.passault@gmail.com>
*/
interface PhraseBuilderInterface
{
/**
* Generates random phrase of given length with given charset
*/
public function build($length, $charset);
/**
* "Niceize" a code
*/
public function niceize($str);
}

@ -0,0 +1,109 @@
Captcha
=======
![Captchas examples](http://gregwar.com/captchas.png)
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YUXRLWHQSWS6L)
Installation
============
With composer :
``` json
{
...
"require": {
"gregwar/captcha": "1.*"
}
}
```
Usage
=====
You can create a captcha with the `CaptchaBuilder` :
```php
<?php
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
```
You can then save it to a file :
```php
<?php
$builder->save('out.jpg');
```
Or output it directly :
```php
<?php
header('Content-type: image/jpeg');
$builder->output();
```
Or inline it directly in the HTML page:
```php
<img src="<?php echo $builder->inline(); ?>" />
```
You'll be able to get the code and compare it with a user input :
```php
<?php
// Example: storing the phrase in the session to test for the user
// input later
$_SESSION['phrase'] = $builder->getPhrase();
```
You can compare the phrase with user input:
```php
if($builder->testPhrase($userInput)) {
// instructions if user phrase is good
}
else {
// user phrase is wrong
}
```
API
===
You can use theses functions :
* **__construct($phrase = null)**, constructs the builder with the given phrase, if the phrase is null, a random one will be generated
* **getPhrase()**, allow you to get the phrase contents
* **setDistortion($distortion)**, enable or disable the distortion, call it before `build()`
* **isOCRReadable()**, returns `true` if the OCR can be read using the `ocrad` software, you'll need to have shell_exec enabled, imagemagick and ocrad installed
* **buildAgainstOCR($width = 150, $height = 40, $font = null)**, builds a code until it is not readable by `ocrad`
* **build($width = 150, $height = 40, $font = null)**, builds a code with the given $width, $height and $font. By default, a random font will be used from the library
* **save($filename, $quality = 80)**, saves the captcha into a jpeg in the $filename, with the given quality
* **get($quality = 80)**, returns the jpeg data
* **output($quality = 80)**, directly outputs the jpeg code to a browser
* **setBackgroundColor($r, $g, $b)**, sets the background color to force it (this will disable many effects and is not recommended)
* **setBackgroundImages(array($imagepath1, $imagePath2))**, Sets custom background images to be used as captcha background. It is recommended to disable image effects when passing custom images for background (ignore_all_effects). A random image is selected from the list passed, the full paths to the image files must be passed.
* **setInterpolation($interpolate)**, enable or disable the interpolation (enabled by default), disabling it will be quicker but the images will look uglier
* **setIgnoreAllEffects($ignoreAllEffects)**, disable all effects on the captcha image. Recommended to use when passing custom background images for the captcha.
* **testPhrase($phrase)**, returns true if the given phrase is good
* **setMaxBehindLines($lines)**, sets the maximum number of lines behind the code
* **setMaxFrontLines($lines)**, sets the maximum number of lines on the front of the code
Symfony 2 Bundle
================
You can have a look at the following repository to enjoy the Symfony 2 bundle packaging this captcha generator :
https://github.com/Gregwar/CaptchaBundle
License
=======
This library is under MIT license, have a look to the `LICENSE` file

@ -0,0 +1,16 @@
<?php
/**
* Registers an autoload for all the classes in Gregwar\Captcha
*/
spl_autoload_register(function ($className) {
$namespace = 'Gregwar\\Captcha';
if (strpos($className, $namespace) === 0) {
$className = str_replace($namespace, '', $className);
$fileName = __DIR__ . '/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($fileName)) {
require($fileName);
}
}
});

@ -0,0 +1,28 @@
{
"name": "gregwar/captcha",
"type": "captcha",
"description": "Captcha generator",
"keywords": ["captcha", "spam", "bot"],
"homepage": "https://github.com/Gregwar/Captcha",
"license": "MIT",
"authors": [
{
"name": "Grégoire Passault",
"email": "g.passault@gmail.com",
"homepage": "http://www.gregwar.com/"
},
{
"name": "Jeremy Livingston",
"email": "jeremy.j.livingston@gmail.com"
}
],
"require": {
"php": ">=5.3.0",
"ext-gd": "*"
},
"autoload": {
"psr-4": {
"Gregwar\\Captcha\\": "/"
}
}
}

@ -0,0 +1,14 @@
<?php
include(__DIR__.'/../CaptchaBuilderInterface.php');
include(__DIR__.'/../PhraseBuilderInterface.php');
include(__DIR__.'/../CaptchaBuilder.php');
include(__DIR__.'/../PhraseBuilder.php');
use Gregwar\Captcha\CaptchaBuilder;
$captcha = new CaptchaBuilder;
$captcha
->build()
->save('out.jpg')
;

@ -0,0 +1,15 @@
<?php
include(__DIR__.'/../CaptchaBuilderInterface.php');
include(__DIR__.'/../PhraseBuilderInterface.php');
include(__DIR__.'/../CaptchaBuilder.php');
include(__DIR__.'/../PhraseBuilder.php');
use Gregwar\Captcha\CaptchaBuilder;
echo count(CaptchaBuilder::create()
->build()
->getFingerprint()
);
echo "\n";

@ -0,0 +1,15 @@
<!DOCTYPE html>
<body>
<html>
<meta charset="utf-8" />
</html>
<body>
<h1>Captchas gallery</h1>
<?php for ($x=0; $x<8; $x++) { ?>
<?php for ($y=0; $y<5; $y++) { ?>
<img src="output.php?n=<?php echo 5*$x+$y; ?>" />
<?php } ?>
<br />
<?php } ?>
</body>
</body>

@ -0,0 +1,42 @@
<?php
include(__DIR__.'/../CaptchaBuilderInterface.php');
include(__DIR__.'/../PhraseBuilderInterface.php');
include(__DIR__.'/../CaptchaBuilder.php');
include(__DIR__.'/../PhraseBuilder.php');
use Gregwar\Captcha\CaptchaBuilder;
/**
* Generates 1000 captchas and try to read their code with the
* ocrad OCR
*/
$tests = 10000;
$passed = 0;
shell_exec('rm passed*.jpg');
for ($i=0; $i<$tests; $i++) {
echo "Captcha $i/$tests... ";
$captcha = new CaptchaBuilder;
$captcha
->setDistortion(false)
->build()
;
if ($captcha->isOCRReadable()) {
$passed++;
$captcha->save("passed$passed.jpg");
echo "passed at ocr... ";
} else {
echo "failed... ";
}
echo "pass rate: ".round(100*$passed/($i+1),2)."%\n";
}
echo "\n";
echo "Over, $passed/$tests readed with OCR\n";

@ -0,0 +1,15 @@
<?php
include(__DIR__.'/../CaptchaBuilderInterface.php');
include(__DIR__.'/../PhraseBuilderInterface.php');
include(__DIR__.'/../CaptchaBuilder.php');
include(__DIR__.'/../PhraseBuilder.php');
use Gregwar\Captcha\CaptchaBuilder;
header('Content-type: image/jpeg');
CaptchaBuilder::create()
->build()
->output()
;

@ -0,0 +1 @@
Non-security issues and pull requests are no longer being accepted for the legacy PHPMailer 5.2 branch. Migrate to PHPMailer 6.0 (or later) and report your issue there.

@ -0,0 +1 @@
Non-security issues and pull requests are no longer being accepted for the legacy PHPMailer 5.2 branch. Migrate to PHPMailer 6.0 (or later) and report your issue there.

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

@ -0,0 +1,49 @@
<?php
/**
* PHPMailer SPL autoloader.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer SPL autoloader.
* @param string $classname The name of the class to load
*/
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* @param string $classname The name of the class to load
*/
function __autoload($classname)
{
PHPMailerAutoload($classname);
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,197 @@
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.4
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailerOAuth - PHPMailer subclass adding OAuth support.
* @package PHPMailer
* @author @sherryl4george
* @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk>
*/
class PHPMailerOAuth extends PHPMailer
{
/**
* The OAuth user's email address
* @var string
*/
public $oauthUserEmail = '';
/**
* The OAuth refresh token
* @var string
*/
public $oauthRefreshToken = '';
/**
* The OAuth client ID
* @var string
*/
public $oauthClientId = '';
/**
* The OAuth client secret
* @var string
*/
public $oauthClientSecret = '';
/**
* An instance of the PHPMailerOAuthGoogle class.
* @var PHPMailerOAuthGoogle
* @access protected
*/
protected $oauth = null;
/**
* Get a PHPMailerOAuthGoogle instance to use.
* @return PHPMailerOAuthGoogle
*/
public function getOAUTHInstance()
{
if (!is_object($this->oauth)) {
$this->oauth = new PHPMailerOAuthGoogle(
$this->oauthUserEmail,
$this->oauthClientSecret,
$this->oauthClientId,
$this->oauthRefreshToken
);
}
return $this->oauth;
}
/**
* Initiate a connection to an SMTP server.
* Overrides the original smtpConnect method to add support for OAuth.
* @param array $options An array of options compatible with stream_context_create()
* @uses SMTP
* @access public
* @return bool
* @throws phpmailerException
*/
public function smtpConnect($options = array())
{
if (is_null($this->smtp)) {
$this->smtp = $this->getSMTPInstance();
}
if (is_null($this->oauth)) {
$this->oauth = $this->getOAUTHInstance();
}
// Already connected?
if ($this->smtp->connected()) {
return true;
}
$this->smtp->setTimeout($this->Timeout);
$this->smtp->setDebugLevel($this->SMTPDebug);
$this->smtp->setDebugOutput($this->Debugoutput);
$this->smtp->setVerp($this->do_verp);
$hosts = explode(';', $this->Host);
$lastexception = null;
foreach ($hosts as $hostentry) {
$hostinfo = array();
if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
// Not a valid host entry
continue;
}
// $hostinfo[2]: optional ssl or tls prefix
// $hostinfo[3]: the hostname
// $hostinfo[4]: optional port number
// The host string prefix can temporarily override the current setting for SMTPSecure
// If it's not specified, the default value is used
$prefix = '';
$secure = $this->SMTPSecure;
$tls = ($this->SMTPSecure == 'tls');
if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
$prefix = 'ssl://';
$tls = false; // Can't have SSL and TLS at the same time
$secure = 'ssl';
} elseif ($hostinfo[2] == 'tls') {
$tls = true;
// tls doesn't use a prefix
$secure = 'tls';
}
//Do we need the OpenSSL extension?
$sslext = defined('OPENSSL_ALGO_SHA1');
if ('tls' === $secure or 'ssl' === $secure) {
//Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
if (!$sslext) {
throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
}
}
$host = $hostinfo[3];
$port = $this->Port;
$tport = (integer)$hostinfo[4];
if ($tport > 0 and $tport < 65536) {
$port = $tport;
}
if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
try {
if ($this->Helo) {
$hello = $this->Helo;
} else {
$hello = $this->serverHostname();
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
// * it's not disabled
// * we have openssl extension
// * we are not already using SSL
// * the server offers STARTTLS
if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if ($tls) {
if (!$this->smtp->startTLS()) {
throw new phpmailerException($this->lang('connect_host'));
}
// We must resend HELO after tls negotiation
$this->smtp->hello($hello);
}
if ($this->SMTPAuth) {
if (!$this->smtp->authenticate(
$this->Username,
$this->Password,
$this->AuthType,
$this->Realm,
$this->Workstation,
$this->oauth
)
) {
throw new phpmailerException($this->lang('authenticate'));
}
}
return true;
} catch (phpmailerException $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
// We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
// If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
// As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions and !is_null($lastexception)) {
throw $lastexception;
}
return false;
}
}

@ -0,0 +1,77 @@
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.4
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailerOAuthGoogle - Wrapper for League OAuth2 Google provider.
* @package PHPMailer
* @author @sherryl4george
* @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk>
* @link https://github.com/thephpleague/oauth2-client
*/
class PHPMailerOAuthGoogle
{
private $oauthUserEmail = '';
private $oauthRefreshToken = '';
private $oauthClientId = '';
private $oauthClientSecret = '';
/**
* @param string $UserEmail
* @param string $ClientSecret
* @param string $ClientId
* @param string $RefreshToken
*/
public function __construct(
$UserEmail,
$ClientSecret,
$ClientId,
$RefreshToken
) {
$this->oauthClientId = $ClientId;
$this->oauthClientSecret = $ClientSecret;
$this->oauthRefreshToken = $RefreshToken;
$this->oauthUserEmail = $UserEmail;
}
private function getProvider()
{
return new League\OAuth2\Client\Provider\Google([
'clientId' => $this->oauthClientId,
'clientSecret' => $this->oauthClientSecret
]);
}
private function getGrant()
{
return new \League\OAuth2\Client\Grant\RefreshToken();
}
private function getToken()
{
$provider = $this->getProvider();
$grant = $this->getGrant();
return $provider->getAccessToken($grant, ['refresh_token' => $this->oauthRefreshToken]);
}
public function getOauth64()
{
$token = $this->getToken();
return base64_encode("user=" . $this->oauthUserEmail . "\001auth=Bearer " . $token . "\001\001");
}
}

@ -0,0 +1,407 @@
<?php
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication.
* Does not support APOP.
* @package PHPMailer
* @author Richard Davey (original author) <rich@corephp.co.uk>
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
*/
class POP3
{
/**
* The POP3 PHPMailer Version number.
* @var string
* @access public
*/
public $Version = '5.2.25';
/**
* Default POP3 port number.
* @var integer
* @access public
*/
public $POP3_PORT = 110;
/**
* Default timeout in seconds.
* @var integer
* @access public
*/
public $POP3_TIMEOUT = 30;
/**
* POP3 Carriage Return + Line Feed.
* @var string
* @access public
* @deprecated Use the constant instead
*/
public $CRLF = "\r\n";
/**
* Debug display level.
* Options: 0 = no, 1+ = yes
* @var integer
* @access public
*/
public $do_debug = 0;
/**
* POP3 mail server hostname.
* @var string
* @access public
*/
public $host;
/**
* POP3 port number.
* @var integer
* @access public
*/
public $port;
/**
* POP3 Timeout Value in seconds.
* @var integer
* @access public
*/
public $tval;
/**
* POP3 username
* @var string
* @access public
*/
public $username;
/**
* POP3 password.
* @var string
* @access public
*/
public $password;
/**
* Resource handle for the POP3 connection socket.
* @var resource
* @access protected
*/
protected $pop_conn;
/**
* Are we connected?
* @var boolean
* @access protected
*/
protected $connected = false;
/**
* Error container.
* @var array
* @access protected
*/
protected $errors = array();
/**
* Line break constant
*/
const CRLF = "\r\n";
/**
* Simple static wrapper for all-in-one POP before SMTP
* @param $host
* @param integer|boolean $port The port number to connect to
* @param integer|boolean $timeout The timeout value
* @param string $username
* @param string $password
* @param integer $debug_level
* @return boolean
*/
public static function popBeforeSmtp(
$host,
$port = false,
$timeout = false,
$username = '',
$password = '',
$debug_level = 0
) {
$pop = new POP3;
return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level);
}
/**
* Authenticate with a POP3 server.
* A connect, login, disconnect sequence
* appropriate for POP-before SMTP authorisation.
* @access public
* @param string $host The hostname to connect to
* @param integer|boolean $port The port number to connect to
* @param integer|boolean $timeout The timeout value
* @param string $username
* @param string $password
* @param integer $debug_level
* @return boolean
*/
public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0)
{
$this->host = $host;
// If no port value provided, use default
if (false === $port) {
$this->port = $this->POP3_PORT;
} else {
$this->port = (integer)$port;
}
// If no timeout value provided, use default
if (false === $timeout) {
$this->tval = $this->POP3_TIMEOUT;
} else {
$this->tval = (integer)$timeout;
}
$this->do_debug = $debug_level;
$this->username = $username;
$this->password = $password;
// Reset the error log
$this->errors = array();
// connect
$result = $this->connect($this->host, $this->port, $this->tval);
if ($result) {
$login_result = $this->login($this->username, $this->password);
if ($login_result) {
$this->disconnect();
return true;
}
}
// We need to disconnect regardless of whether the login succeeded
$this->disconnect();
return false;
}
/**
* Connect to a POP3 server.
* @access public
* @param string $host
* @param integer|boolean $port
* @param integer $tval
* @return boolean
*/
public function connect($host, $port = false, $tval = 30)
{
// Are we already connected?
if ($this->connected) {
return true;
}
//On Windows this will raise a PHP Warning error if the hostname doesn't exist.
//Rather than suppress it with @fsockopen, capture it cleanly instead
set_error_handler(array($this, 'catchWarning'));
if (false === $port) {
$port = $this->POP3_PORT;
}
// connect to the POP3 server
$this->pop_conn = fsockopen(
$host, // POP3 Host
$port, // Port #
$errno, // Error Number
$errstr, // Error Message
$tval
); // Timeout (seconds)
// Restore the error handler
restore_error_handler();
// Did we connect?
if (false === $this->pop_conn) {
// It would appear not...
$this->setError(array(
'error' => "Failed to connect to server $host on port $port",
'errno' => $errno,
'errstr' => $errstr
));
return false;
}
// Increase the stream time-out
stream_set_timeout($this->pop_conn, $tval, 0);
// Get the POP3 server response
$pop3_response = $this->getResponse();
// Check for the +OK
if ($this->checkResponse($pop3_response)) {
// The connection is established and the POP3 server is talking
$this->connected = true;
return true;
}
return false;
}
/**
* Log in to the POP3 server.
* Does not support APOP (RFC 2828, 4949).
* @access public
* @param string $username
* @param string $password
* @return boolean
*/
public function login($username = '', $password = '')
{
if (!$this->connected) {
$this->setError('Not connected to POP3 server');
}
if (empty($username)) {
$username = $this->username;
}
if (empty($password)) {
$password = $this->password;
}
// Send the Username
$this->sendString("USER $username" . self::CRLF);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
// Send the Password
$this->sendString("PASS $password" . self::CRLF);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
return true;
}
}
return false;
}
/**
* Disconnect from the POP3 server.
* @access public
*/
public function disconnect()
{
$this->sendString('QUIT');
//The QUIT command may cause the daemon to exit, which will kill our connection
//So ignore errors here
try {
@fclose($this->pop_conn);
} catch (Exception $e) {
//Do nothing
};
}
/**
* Get a response from the POP3 server.
* $size is the maximum number of bytes to retrieve
* @param integer $size
* @return string
* @access protected
*/
protected function getResponse($size = 128)
{
$response = fgets($this->pop_conn, $size);
if ($this->do_debug >= 1) {
echo "Server -> Client: $response";
}
return $response;
}
/**
* Send raw data to the POP3 server.
* @param string $string
* @return integer
* @access protected
*/
protected function sendString($string)
{
if ($this->pop_conn) {
if ($this->do_debug >= 2) { //Show client messages when debug >= 2
echo "Client -> Server: $string";
}
return fwrite($this->pop_conn, $string, strlen($string));
}
return 0;
}
/**
* Checks the POP3 server response.
* Looks for for +OK or -ERR.
* @param string $string
* @return boolean
* @access protected
*/
protected function checkResponse($string)
{
if (substr($string, 0, 3) !== '+OK') {
$this->setError(array(
'error' => "Server reported an error: $string",
'errno' => 0,
'errstr' => ''
));
return false;
} else {
return true;
}
}
/**
* Add an error to the internal error store.
* Also display debug output if it's enabled.
* @param $error
* @access protected
*/
protected function setError($error)
{
$this->errors[] = $error;
if ($this->do_debug >= 1) {
echo '<pre>';
foreach ($this->errors as $error) {
print_r($error);
}
echo '</pre>';
}
}
/**
* Get an array of error messages, if any.
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* POP3 connection error handler.
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
* @access protected
*/
protected function catchWarning($errno, $errstr, $errfile, $errline)
{
$this->setError(array(
'error' => "Connecting to the POP3 server raised a PHP warning: ",
'errno' => $errno,
'errstr' => $errstr,
'errfile' => $errfile,
'errline' => $errline
));
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,61 @@
{
"name": "phpmailer/phpmailer",
"type": "library",
"description": "PHPMailer is a full-featured email creation and transfer class for PHP",
"authors": [
{
"name": "Marcus Bointon",
"email": "phpmailer@synchromedia.co.uk"
},
{
"name": "Jim Jagielski",
"email": "jimjag@gmail.com"
},
{
"name": "Andy Prevost",
"email": "codeworxtech@users.sourceforge.net"
},
{
"name": "Brent R. Matzelle"
}
],
"require": {
"ext-ctype": "*",
"php": ">=5.0.0"
},
"require-dev": {
"doctrine/annotations": "1.2.*",
"jms/serializer": "0.16.*",
"phpdocumentor/phpdocumentor": "2.*",
"phpunit/phpunit": "4.8.*",
"symfony/debug": "2.8.*",
"symfony/filesystem": "2.8.*",
"symfony/translation": "2.8.*",
"symfony/yaml": "2.8.*",
"zendframework/zend-cache": "2.5.1",
"zendframework/zend-config": "2.5.1",
"zendframework/zend-eventmanager": "2.5.1",
"zendframework/zend-filter": "2.5.1",
"zendframework/zend-i18n": "2.5.1",
"zendframework/zend-json": "2.5.1",
"zendframework/zend-math": "2.5.1",
"zendframework/zend-serializer": "2.5.*",
"zendframework/zend-servicemanager": "2.5.*",
"zendframework/zend-stdlib": "2.5.1"
},
"suggest": {
"league/oauth2-google": "Needed for Google XOAUTH2 authentication"
},
"autoload": {
"classmap": [
"class.phpmailer.php",
"class.phpmaileroauth.php",
"class.phpmaileroauthgoogle.php",
"class.smtp.php",
"class.pop3.php",
"extras/EasyPeasyICS.php",
"extras/ntlm_sasl_client.php"
]
},
"license": "LGPL-2.1"
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,148 @@
<?php
/**
* EasyPeasyICS Simple ICS/vCal data generator.
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
* @author Manuel Reinhard <manu@sprain.ch>
*
* Built with inspiration from
* http://stackoverflow.com/questions/1463480/how-can-i-use-php-to-dynamically-publish-an-ical-file-to-be-read-by-google-calend/1464355#1464355
* History:
* 2010/12/17 - Manuel Reinhard - when it all started
* 2014 PHPMailer project becomes maintainer
*/
/**
* Class EasyPeasyICS.
* Simple ICS data generator
* @package phpmailer
* @subpackage easypeasyics
*/
class EasyPeasyICS
{
/**
* The name of the calendar
* @var string
*/
protected $calendarName;
/**
* The array of events to add to this calendar
* @var array
*/
protected $events = array();
/**
* Constructor
* @param string $calendarName
*/
public function __construct($calendarName = "")
{
$this->calendarName = $calendarName;
}
/**
* Add an event to this calendar.
* @param string $start The start date and time as a unix timestamp
* @param string $end The end date and time as a unix timestamp
* @param string $summary A summary or title for the event
* @param string $description A description of the event
* @param string $url A URL for the event
* @param string $uid A unique identifier for the event - generated automatically if not provided
* @return array An array of event details, including any generated UID
*/
public function addEvent($start, $end, $summary = '', $description = '', $url = '', $uid = '')
{
if (empty($uid)) {
$uid = md5(uniqid(mt_rand(), true)) . '@EasyPeasyICS';
}
$event = array(
'start' => gmdate('Ymd', $start) . 'T' . gmdate('His', $start) . 'Z',
'end' => gmdate('Ymd', $end) . 'T' . gmdate('His', $end) . 'Z',
'summary' => $summary,
'description' => $description,
'url' => $url,
'uid' => $uid
);
$this->events[] = $event;
return $event;
}
/**
* @return array Get the array of events.
*/
public function getEvents()
{
return $this->events;
}
/**
* Clear all events.
*/
public function clearEvents()
{
$this->events = array();
}
/**
* Get the name of the calendar.
* @return string
*/
public function getName()
{
return $this->calendarName;
}
/**
* Set the name of the calendar.
* @param $name
*/
public function setName($name)
{
$this->calendarName = $name;
}
/**
* Render and optionally output a vcal string.
* @param bool $output Whether to output the calendar data directly (the default).
* @return string The complete rendered vlal
*/
public function render($output = true)
{
//Add header
$ics = 'BEGIN:VCALENDAR
METHOD:PUBLISH
VERSION:2.0
X-WR-CALNAME:' . $this->calendarName . '
PRODID:-//hacksw/handcal//NONSGML v1.0//EN';
//Add events
foreach ($this->events as $event) {
$ics .= '
BEGIN:VEVENT
UID:' . $event['uid'] . '
DTSTAMP:' . gmdate('Ymd') . 'T' . gmdate('His') . 'Z
DTSTART:' . $event['start'] . '
DTEND:' . $event['end'] . '
SUMMARY:' . str_replace("\n", "\\n", $event['summary']) . '
DESCRIPTION:' . str_replace("\n", "\\n", $event['description']) . '
URL;VALUE=URI:' . $event['url'] . '
END:VEVENT';
}
//Add footer
$ics .= '
END:VCALENDAR';
if ($output) {
//Output
$filename = $this->calendarName;
//Filename needs quoting if it contains spaces
if (strpos($filename, ' ') !== false) {
$filename = '"'.$filename.'"';
}
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=' . $filename . '.ics');
echo $ics;
}
return $ics;
}
}

@ -0,0 +1,17 @@
# PHPMailer Extras
These classes provide optional additional functions to PHPMailer.
These are not loaded by the PHPMailer autoloader, so in some cases you may need to `require` them yourself before using them.
## EasyPeasyICS
This class was originally written by Manuel Reinhard and provides a simple means of generating ICS/vCal files that are used in sending calendar events. PHPMailer does not use it directly, but you can use it to generate content appropriate for placing in the `Ical` property of PHPMailer. The PHPMailer project is now its official home as Manuel has given permission for that and is no longer maintaining it himself.
## htmlfilter
This class by Konstantin Riabitsev and Jim Jagielski implements HTML filtering to remove potentially malicious tags, such as `<script>` or `onclick=` attributes that can result in XSS attacks. This is a simple filter and is not as comprehensive as [HTMLawed](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/) or [HTMLPurifier](http://htmlpurifier.org), but it's easier to use and considerably better than nothing! PHPMailer does not use it directly, but you may want to apply it to user-supplied HTML before using it as a message body.
## NTLM_SASL_client
This class by Manuel Lemos (bundled with permission) adds the ability to authenticate with Microsoft Windows mail servers that use NTLM-based authentication. It is used by PHPMailer if you send via SMTP and set the `AuthType` property to `NTLM`; you will also need to use the `Realm` and `Workstation` properties. The original source is [here](http://www.phpclasses.org/browse/file/7495.html).

File diff suppressed because it is too large Load Diff

@ -0,0 +1,185 @@
<?php
/*
* ntlm_sasl_client.php
*
* @(#) $Id: ntlm_sasl_client.php,v 1.3 2004/11/17 08:00:37 mlemos Exp $
*
*/
define("SASL_NTLM_STATE_START", 0);
define("SASL_NTLM_STATE_IDENTIFY_DOMAIN", 1);
define("SASL_NTLM_STATE_RESPOND_CHALLENGE", 2);
define("SASL_NTLM_STATE_DONE", 3);
define("SASL_FAIL", -1);
define("SASL_CONTINUE", 1);
class ntlm_sasl_client_class
{
public $credentials = array();
public $state = SASL_NTLM_STATE_START;
public function initialize(&$client)
{
if (!function_exists($function = "mcrypt_encrypt")
|| !function_exists($function = "mhash")
) {
$extensions = array(
"mcrypt_encrypt" => "mcrypt",
"mhash" => "mhash"
);
$client->error = "the extension " . $extensions[$function] .
" required by the NTLM SASL client class is not available in this PHP configuration";
return (0);
}
return (1);
}
public function ASCIIToUnicode($ascii)
{
for ($unicode = "", $a = 0; $a < strlen($ascii); $a++) {
$unicode .= substr($ascii, $a, 1) . chr(0);
}
return ($unicode);
}
public function typeMsg1($domain, $workstation)
{
$domain_length = strlen($domain);
$workstation_length = strlen($workstation);
$workstation_offset = 32;
$domain_offset = $workstation_offset + $workstation_length;
return (
"NTLMSSP\0" .
"\x01\x00\x00\x00" .
"\x07\x32\x00\x00" .
pack("v", $domain_length) .
pack("v", $domain_length) .
pack("V", $domain_offset) .
pack("v", $workstation_length) .
pack("v", $workstation_length) .
pack("V", $workstation_offset) .
$workstation .
$domain
);
}
public function NTLMResponse($challenge, $password)
{
$unicode = $this->ASCIIToUnicode($password);
$md4 = mhash(MHASH_MD4, $unicode);
$padded = $md4 . str_repeat(chr(0), 21 - strlen($md4));
$iv_size = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
for ($response = "", $third = 0; $third < 21; $third += 7) {
for ($packed = "", $p = $third; $p < $third + 7; $p++) {
$packed .= str_pad(decbin(ord(substr($padded, $p, 1))), 8, "0", STR_PAD_LEFT);
}
for ($key = "", $p = 0; $p < strlen($packed); $p += 7) {
$s = substr($packed, $p, 7);
$b = $s . ((substr_count($s, "1") % 2) ? "0" : "1");
$key .= chr(bindec($b));
}
$ciphertext = mcrypt_encrypt(MCRYPT_DES, $key, $challenge, MCRYPT_MODE_ECB, $iv);
$response .= $ciphertext;
}
return $response;
}
public function typeMsg3($ntlm_response, $user, $domain, $workstation)
{
$domain_unicode = $this->ASCIIToUnicode($domain);
$domain_length = strlen($domain_unicode);
$domain_offset = 64;
$user_unicode = $this->ASCIIToUnicode($user);
$user_length = strlen($user_unicode);
$user_offset = $domain_offset + $domain_length;
$workstation_unicode = $this->ASCIIToUnicode($workstation);
$workstation_length = strlen($workstation_unicode);
$workstation_offset = $user_offset + $user_length;
$lm = "";
$lm_length = strlen($lm);
$lm_offset = $workstation_offset + $workstation_length;
$ntlm = $ntlm_response;
$ntlm_length = strlen($ntlm);
$ntlm_offset = $lm_offset + $lm_length;
$session = "";
$session_length = strlen($session);
$session_offset = $ntlm_offset + $ntlm_length;
return (
"NTLMSSP\0" .
"\x03\x00\x00\x00" .
pack("v", $lm_length) .
pack("v", $lm_length) .
pack("V", $lm_offset) .
pack("v", $ntlm_length) .
pack("v", $ntlm_length) .
pack("V", $ntlm_offset) .
pack("v", $domain_length) .
pack("v", $domain_length) .
pack("V", $domain_offset) .
pack("v", $user_length) .
pack("v", $user_length) .
pack("V", $user_offset) .
pack("v", $workstation_length) .
pack("v", $workstation_length) .
pack("V", $workstation_offset) .
pack("v", $session_length) .
pack("v", $session_length) .
pack("V", $session_offset) .
"\x01\x02\x00\x00" .
$domain_unicode .
$user_unicode .
$workstation_unicode .
$lm .
$ntlm
);
}
public function start(&$client, &$message, &$interactions)
{
if ($this->state != SASL_NTLM_STATE_START) {
$client->error = "NTLM authentication state is not at the start";
return (SASL_FAIL);
}
$this->credentials = array(
"user" => "",
"password" => "",
"realm" => "",
"workstation" => ""
);
$defaults = array();
$status = $client->GetCredentials($this->credentials, $defaults, $interactions);
if ($status == SASL_CONTINUE) {
$this->state = SASL_NTLM_STATE_IDENTIFY_DOMAIN;
}
unset($message);
return ($status);
}
public function step(&$client, $response, &$message, &$interactions)
{
switch ($this->state) {
case SASL_NTLM_STATE_IDENTIFY_DOMAIN:
$message = $this->typeMsg1($this->credentials["realm"], $this->credentials["workstation"]);
$this->state = SASL_NTLM_STATE_RESPOND_CHALLENGE;
break;
case SASL_NTLM_STATE_RESPOND_CHALLENGE:
$ntlm_response = $this->NTLMResponse(substr($response, 24, 8), $this->credentials["password"]);
$message = $this->typeMsg3(
$ntlm_response,
$this->credentials["user"],
$this->credentials["realm"],
$this->credentials["workstation"]
);
$this->state = SASL_NTLM_STATE_DONE;
break;
case SASL_NTLM_STATE_DONE:
$client->error = "NTLM authentication was finished without success";
return (SASL_FAIL);
default:
$client->error = "invalid NTLM authentication step state";
return (SASL_FAIL);
}
return (SASL_CONTINUE);
}
}

@ -0,0 +1,162 @@
<?php
/**
* Get an OAuth2 token from Google.
* * Install this script on your server so that it's accessible
* as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
* e.g.: http://localhost/phpmail/get_oauth_token.php
* * Ensure dependencies are installed with 'composer install'
* * Set up an app in your Google developer console
* * Set the script address as the app's redirect URL
* If no refresh token is obtained when running this file, revoke access to your app
* using link: https://accounts.google.com/b/0/IssuedAuthSubTokens and run the script again.
* This script requires PHP 5.4 or later
* PHP Version 5.4
*/
namespace League\OAuth2\Client\Provider;
require 'vendor/autoload.php';
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
session_start();
//If this automatic URL doesn't work, set it yourself manually
$redirectUri = isset($_SERVER['HTTPS']) ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//$redirectUri = 'http://localhost/phpmailer/get_oauth_token.php';
//These details obtained are by setting up app in Google developer console.
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
class Google extends AbstractProvider
{
use BearerAuthorizationTrait;
const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'id';
/**
* @var string If set, this will be sent to google as the "access_type" parameter.
* @link https://developers.google.com/accounts/docs/OAuth2WebServer#offline
*/
protected $accessType;
/**
* @var string If set, this will be sent to google as the "hd" parameter.
* @link https://developers.google.com/accounts/docs/OAuth2Login#hd-param
*/
protected $hostedDomain;
/**
* @var string If set, this will be sent to google as the "scope" parameter.
* @link https://developers.google.com/gmail/api/auth/scopes
*/
protected $scope;
public function getBaseAuthorizationUrl()
{
return 'https://accounts.google.com/o/oauth2/auth';
}
public function getBaseAccessTokenUrl(array $params)
{
return 'https://accounts.google.com/o/oauth2/token';
}
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return ' ';
}
protected function getAuthorizationParameters(array $options)
{
if (is_array($this->scope)) {
$separator = $this->getScopeSeparator();
$this->scope = implode($separator, $this->scope);
}
$params = array_merge(
parent::getAuthorizationParameters($options),
array_filter([
'hd' => $this->hostedDomain,
'access_type' => $this->accessType,
'scope' => $this->scope,
// if the user is logged in with more than one account ask which one to use for the login!
'authuser' => '-1'
])
);
return $params;
}
protected function getDefaultScopes()
{
return [
'email',
'openid',
'profile',
];
}
protected function getScopeSeparator()
{
return ' ';
}
protected function checkResponse(ResponseInterface $response, $data)
{
if (!empty($data['error'])) {
$code = 0;
$error = $data['error'];
if (is_array($error)) {
$code = $error['code'];
$error = $error['message'];
}
throw new IdentityProviderException($error, $code, $data);
}
}
protected function createResourceOwner(array $response, AccessToken $token)
{
return new GoogleUser($response);
}
}
//Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
$provider = new Google(
array(
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'scope' => array('https://mail.google.com/'),
'accessType' => 'offline'
)
);
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken(
'authorization_code',
array(
'code' => $_GET['code']
)
);
// Use this to get a new access token if the old one expires
echo 'Refresh Token: ' . $token->getRefreshToken();
}

@ -1 +1 @@
Subproject commit 93be2e7f3add62850aea31149a472bd509f89f2d
Subproject commit 95178cb6bf55d9bc2b7e2a0be59b3d8aee430f7a
Loading…
Cancel
Save