Merge branch 'develop' into Eole_Graph
Conflicts: client/index.html client/js/controllers/home/home.js client/partials/home/home.html
This commit is contained in:
commit
49f416dc50
317 changed files with 5578 additions and 33526 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -1 +1 @@
|
|||
/nbproject
|
||||
nbproject
|
19
client/Test/index.html
Normal file
19
client/Test/index.html
Normal file
|
@ -0,0 +1,19 @@
|
|||
<head>
|
||||
|
||||
<script src="../vendors/angularjs/angular.min.js"></script>
|
||||
<script src="../vendors/angularjs/angular-route.min.js"></script>
|
||||
<script src="../vendors/angularjs/angular-sanitize.min.js"></script>
|
||||
<script src="../vendors/angularjs/angular-cookies.min.js"></script>
|
||||
<script src="../js/services/Test.js"></script>
|
||||
<script src="../js/app.js"></script>
|
||||
</head>
|
||||
|
||||
<body ng-app="mainApp">
|
||||
<div ng-controller="hassan">
|
||||
<ul>
|
||||
<li ng-repeat="person in persons">
|
||||
{{person.Name + ' : ' + person.Age}}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</body>
|
39
client/index.html
Normal file → Executable file
39
client/index.html
Normal file → Executable file
|
@ -13,27 +13,27 @@
|
|||
<link rel="stylesheet" href="./css/graph.css">
|
||||
|
||||
|
||||
<!--[if lt IE 9]>
|
||||
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
|
||||
<![endif]-->
|
||||
<!--[if lt IE 9]>
|
||||
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
|
||||
<![endif]-->
|
||||
</head>
|
||||
|
||||
|
||||
|
||||
|
||||
<body>
|
||||
|
||||
<!-- Overlay -->
|
||||
<!-- Overlay -->
|
||||
<div ng-include="'./partials/login.html'"></div>
|
||||
<div ng-include="'./partials/home/machineDetails.html'"></div>
|
||||
<div ng-include="'./partials/loading.html'"></div>
|
||||
<div ng-include="'./partials/loading.html'"></div>
|
||||
<div ng-include="'./partials/image/upload.html'"></div>
|
||||
|
||||
|
||||
|
||||
<!-- MAIN GRID -->
|
||||
<div class="container-lg">
|
||||
<!-- Status bar -->
|
||||
<div class="row" ng-controller="statusCtrl">
|
||||
<div class="col-lg-12">
|
||||
<!-- Status bar -->
|
||||
<!-- Status bar -->
|
||||
<div ng-include="'./partials/status.html'"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -59,39 +59,42 @@
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- Include JQuery -->
|
||||
<script src="./vendors/jquery/jquery-2.2.0.min.js"></script>
|
||||
<script src="./vendors/jquery/dmuploader.min.js"></script>
|
||||
|
||||
<!-- Include Bootstrap -->
|
||||
<script src="./vendors/bootstrap/js/bootstrap.min.js"></script>
|
||||
|
||||
|
||||
<!-- Include AngularJS and dependencies-->
|
||||
<script src="./vendors/angularjs/angular.min.js"></script>
|
||||
<script src="./vendors/angularjs/angular-route.min.js"></script>
|
||||
<script src="./vendors/angularjs/angular-sanitize.min.js"></script>
|
||||
<script src="./vendors/angularjs/angular-cookies.min.js"></script>
|
||||
<script src="./vendors/angularjs/angular-upload.min.js"></script>
|
||||
<script src="./js/app.js"></script>
|
||||
|
||||
|
||||
<!-- Include services -->
|
||||
<script src="./js/services/Identity.js"></script>
|
||||
<script src="./js/services/Image.js"></script>
|
||||
<script src="./js/services/Compute.js"></script>
|
||||
<script src="./js/services/Loading.js"></script>
|
||||
|
||||
|
||||
<!-- Include controller -->
|
||||
<script src="./js/controllers/login.js"></script>
|
||||
<script src="./js/controllers/status.js"></script>
|
||||
<script src="./js/controllers/home/home.js"></script>
|
||||
<script src="./js/controllers/home/machineDetails.js"></script>
|
||||
<script src="./js/controllers/network/network.js"></script>
|
||||
<script src="./js/controllers/image/image.js"></script>
|
||||
<script src="./js/controllers/image/image.js"></script>
|
||||
<script src="./js/controllers/image/upload.js"></script>
|
||||
|
||||
<!-- Includes and dependencies for jointJS -->
|
||||
|
||||
|
@ -101,10 +104,6 @@
|
|||
<script src="./vendors/jointjs/lib/dagre.min.js"></script>
|
||||
<script src="./vendors/jointjs/lib/graphlib.min.js"></script>
|
||||
<script src="./vendors/jointjs/plugins/joint.layout.DirectedGraph.min.js"></script>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
* The main app module instance
|
||||
* @type angular.module.angular-1_3_6_L1749.moduleInstance
|
||||
*/
|
||||
var mainApp=angular.module("mainApp",['ngRoute', 'ngSanitize', 'ngCookies']);
|
||||
var mainApp=angular.module("mainApp",['ngRoute', 'ngSanitize', 'ngCookies','lr.upload']);
|
||||
|
||||
/**
|
||||
* Configure routeProvider
|
||||
|
@ -12,19 +12,20 @@ mainApp.config(['$routeProvider', function($routeProvider){
|
|||
|
||||
|
||||
$routeProvider.
|
||||
when('/home',{
|
||||
templateUrl: 'partials/home/home.html',
|
||||
controller: 'homeCtrl'
|
||||
}).
|
||||
when('/network',{
|
||||
templateUrl: 'partials/network/network.html',
|
||||
controller: 'networkCtrl'
|
||||
}).
|
||||
when('/image',{
|
||||
templateUrl: 'partials/image/image.html',
|
||||
controller: 'imageCtrl'
|
||||
}).otherwise({
|
||||
redirectTo: '/'
|
||||
when('/home',{
|
||||
templateUrl: 'partials/home/home.html',
|
||||
controller: 'homeCtrl'
|
||||
}).
|
||||
when('/network',{
|
||||
templateUrl: 'partials/network/network.html',
|
||||
controller: 'networkCtrl'
|
||||
}).
|
||||
when('/image',{
|
||||
templateUrl: 'partials/image/image.html',
|
||||
controller: 'imageCtrl'
|
||||
})
|
||||
.otherwise({
|
||||
redirectTo: '/home'
|
||||
});
|
||||
}]);
|
||||
|
||||
|
|
323
client/js/controllers/home/home.js
Normal file → Executable file
323
client/js/controllers/home/home.js
Normal file → Executable file
|
@ -5,129 +5,116 @@
|
|||
*/
|
||||
mainApp.controller('homeCtrl', [ '$scope', 'Compute', '$rootScope', 'Loading','Identity', 'Image', function ($scope, Compute, $rootScope, Loading, Identity, Image)
|
||||
{
|
||||
console.log("homeCTRl");
|
||||
console.log("test");
|
||||
// Function to call after pull all data about machines
|
||||
var callMeAfterPullData=function(data){
|
||||
$scope.machines=Compute.getData().machines;
|
||||
Loading.stop();
|
||||
}
|
||||
|
||||
;
|
||||
if(Compute.getData().machines == null && Identity.isAlreadyLogin()){
|
||||
Loading.start();
|
||||
Compute.pullData(callMeAfterPullData);
|
||||
}
|
||||
else{
|
||||
if(Identity.isAlreadyLogin()){
|
||||
callMeAfterPullData();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Image.getImages(function(){});
|
||||
|
||||
|
||||
$scope.raiseShowMachineDetailsEvent=function(id){
|
||||
|
||||
var callback=function(){
|
||||
Loading.stop();
|
||||
var data=Compute.getData();
|
||||
$rootScope.$broadcast("showMachineDetailsEvent", data.machines[id], data.axioms);
|
||||
|
||||
}
|
||||
Loading.start();
|
||||
Compute.pullMachines(callback);
|
||||
}
|
||||
|
||||
//adjacencyList, hard-encoded now but will be the result of a request to the server, format may change
|
||||
var vmList = {
|
||||
'vms': [
|
||||
'VM 1',
|
||||
'VM 2',
|
||||
'VM 3',
|
||||
'VM 4',
|
||||
'VM 5',
|
||||
'VM 6',
|
||||
'VM 7',
|
||||
'VM 8',
|
||||
'VM 9',
|
||||
'VM 10'
|
||||
],
|
||||
'links': [
|
||||
['VM 1', 'VM 2', '', ''],
|
||||
['VM 2', 'VM 3', 'I3', 'I4'],
|
||||
['VM 1', 'VM 3', 'I5', 'I6'],
|
||||
['VM 2', 'VM 4', 'I5', 'I6'],
|
||||
['VM 4', 'VM 5', 'I5', 'I6'],
|
||||
['VM 4', 'VM 6', 'I5', 'I6'],
|
||||
['VM 4', 'VM 1', 'I5', 'I6'],
|
||||
['VM 7', 'VM 4', 'I5', 'I6'],
|
||||
['VM 7', 'VM 3', 'I5', 'I6'],
|
||||
['VM 6', 'VM 8', 'I5', 'I6'],
|
||||
['VM 3', 'VM 9', 'I5', 'I6'],
|
||||
['VM 3', 'VM 10', 'I5', 'I6']
|
||||
]
|
||||
//$scope.machines=Compute.getData().machines;
|
||||
Loading.stop();
|
||||
displayMachine();
|
||||
};
|
||||
|
||||
var tryToRetrieveData = function () {
|
||||
// If no data retrieve about machine and user is logged
|
||||
if (Compute.getData().machines == null && Identity.isAlreadyLogin()) {
|
||||
Loading.start(); // Show loading gif
|
||||
Compute.pullData(callMeAfterPullData); // Retrieve data and call the callback
|
||||
} else {
|
||||
// Else if user is logged and data is already retrieve
|
||||
// simply display data
|
||||
if (Identity.isAlreadyLogin()) {
|
||||
callMeAfterPullData(); // Display data
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//Custom element for inserting html
|
||||
joint.shapes.html = {};
|
||||
joint.shapes.html.Element = joint.shapes.basic.Rect.extend({
|
||||
defaults: joint.util.deepSupplement({
|
||||
type: 'html.Element',
|
||||
attrs: {
|
||||
rect: { stroke: 'none', 'fill-opacity': 0 }
|
||||
}
|
||||
}, joint.shapes.basic.Rect.prototype.defaults)
|
||||
});
|
||||
|
||||
//Custom view for this element
|
||||
/*joint.shapes.basic.Rect.ElementView = joint.dia.ElementView.extend({
|
||||
// On user login
|
||||
$scope.$on('loginEvent', function () {
|
||||
tryToRetrieveData();
|
||||
});
|
||||
|
||||
initialize: function() {
|
||||
_.bindAll(this, 'updateBox');
|
||||
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
|
||||
// Function to call from view to display the details of a machine
|
||||
$scope.raiseShowMachineDetailsEvent = function (id) {
|
||||
|
||||
this.$box = $(_.template(this.model.get('html'))());
|
||||
// Prevent paper from handling pointerdown.
|
||||
this.$box.find('input,select').on('mousedown click', function(evt) { evt.stopPropagation(); });
|
||||
// This is an example of reacting on the input change and storing the input data in the cell model.
|
||||
this.$box.find('input').on('change', _.bind(function(evt) {
|
||||
this.model.set('input', $(evt.target).val());
|
||||
}, this));
|
||||
this.$box.find('select').on('change', _.bind(function(evt) {
|
||||
this.model.set('select', $(evt.target).val());
|
||||
}, this));
|
||||
this.$box.find('select').val(this.model.get('select'));
|
||||
this.$box.on('click', function(){
|
||||
$scope.raiseShowMachineDetailsEvent();
|
||||
});
|
||||
// Update the box position whenever the underlying model changes.
|
||||
this.model.on('change', this.updateBox, this);
|
||||
// Remove the box when the model gets removed from the graph.
|
||||
this.model.on('remove', this.removeBox, this);
|
||||
// Stop loading gif and display overlay
|
||||
var callback = function () {
|
||||
Loading.stop();
|
||||
var data = Compute.getData();
|
||||
|
||||
$rootScope.$broadcast("showMachineDetailsEvent", data.machines[id], data.axioms);
|
||||
|
||||
this.updateBox();
|
||||
},
|
||||
render: function() {
|
||||
joint.dia.ElementView.prototype.render.apply(this, arguments);
|
||||
this.paper.$el.prepend(this.$box);
|
||||
this.updateBox();
|
||||
return this;
|
||||
},
|
||||
updateBox: function() {
|
||||
// Set the position and dimension of the box so that it covers the JointJS element.
|
||||
var bbox = this.model.getBBox();
|
||||
// Example of updating the HTML with a data stored in the cell model.
|
||||
this.$box.find('label').text(this.model.get('name'));
|
||||
this.$box.find('span').text(this.model.get('select'));
|
||||
this.$box.css({ width: bbox.width, height: bbox.height, left: bbox.x, top: bbox.y, transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)' });
|
||||
},
|
||||
removeBox: function(evt) {
|
||||
this.$box.remove();
|
||||
}
|
||||
});
|
||||
*/
|
||||
};
|
||||
Loading.start(); // Show loading gif
|
||||
Compute.pullMachines(callback); // Retrieve machine info and display overlay
|
||||
};
|
||||
|
||||
// Try to retrieve data for the first time
|
||||
tryToRetrieveData();
|
||||
|
||||
var displayMachine = function(){
|
||||
console.log("test");
|
||||
var machineNames = [];
|
||||
var i = 0;
|
||||
$.each(Compute.getData().machines, function(){
|
||||
machineNames[i] = [this.name, this.id];
|
||||
i++;
|
||||
})
|
||||
var vmList = {
|
||||
'vms': machineNames
|
||||
/*'links': [
|
||||
['VM 1', 'VM 2', '', ''],
|
||||
['VM 2', 'VM 3', 'I3', 'I4'],
|
||||
['VM 1', 'VM 3', 'I5', 'I6'],
|
||||
['VM 2', 'VM 4', 'I5', 'I6'],
|
||||
['VM 4', 'VM 5', 'I5', 'I6'],
|
||||
['VM 4', 'VM 6', 'I5', 'I6'],
|
||||
['VM 4', 'VM 1', 'I5', 'I6'],
|
||||
['VM 7', 'VM 4', 'I5', 'I6'],
|
||||
['VM 7', 'VM 3', 'I5', 'I6'],
|
||||
['VM 6', 'VM 8', 'I5', 'I6'],
|
||||
['VM 3', 'VM 9', 'I5', 'I6'],
|
||||
['VM 3', 'VM 10', 'I5', 'I6']
|
||||
]*/
|
||||
};
|
||||
//Custom element for inserting html
|
||||
joint.shapes.html = {};
|
||||
joint.shapes.html.Element = joint.shapes.basic.Rect.extend({
|
||||
defaults: joint.util.deepSupplement({
|
||||
type: 'html.Element',
|
||||
attrs: {
|
||||
rect: { stroke: 'none', 'fill-opacity': 0 }
|
||||
}
|
||||
}, joint.shapes.basic.Rect.prototype.defaults)
|
||||
});
|
||||
|
||||
var graph = new joint.dia.Graph;
|
||||
var paper = new joint.dia.Paper({
|
||||
el: $('#graphHolder'),
|
||||
width: $('#graphHolder').width(),
|
||||
//height: test.height,
|
||||
model: graph,
|
||||
gridSize: 1,
|
||||
eractive: false
|
||||
});
|
||||
paper.$el.css('pointer-events', 'none');
|
||||
var cells = buildGraphFromAdjacencyList(vmList);
|
||||
|
||||
graph.addCells(cells);
|
||||
var test = joint.layout.DirectedGraph.layout(graph, {
|
||||
etLinkVertices: false,
|
||||
//Top to bottom generation
|
||||
ankDir: "TB",
|
||||
odeSep: 150,
|
||||
dgeSep: 150,
|
||||
ankSep: 50
|
||||
});
|
||||
|
||||
paper.setDimensions(test.width, test.height);
|
||||
|
||||
$(".Member").bind('click', function() {
|
||||
$scope.raiseShowMachineDetailsEvent($(this).attr('model-id'));
|
||||
});
|
||||
}
|
||||
|
||||
//Read the adjacencyList and build the elements and the links according to it
|
||||
function buildGraphFromAdjacencyList(adjacencyList) {
|
||||
|
||||
|
@ -137,11 +124,9 @@ mainApp.controller('homeCtrl', [ '$scope', 'Compute', '$rootScope', 'Loading','I
|
|||
_.each(adjacencyList['vms'], function(vm) {
|
||||
elements.push(makeElement(vm));
|
||||
});
|
||||
console.log(elements);
|
||||
_.each(adjacencyList['links'], function(link) {
|
||||
links.push(makeLink(link[0], link[1] , link[2], link[3]));
|
||||
});
|
||||
console.log(links);
|
||||
// Links must be added after all the elements. This is because when the links
|
||||
// are added to the graph, link source/target
|
||||
// elements must be in the graph already.
|
||||
|
@ -162,7 +147,8 @@ mainApp.controller('homeCtrl', [ '$scope', 'Compute', '$rootScope', 'Loading','I
|
|||
}
|
||||
|
||||
//Return a new element
|
||||
function makeElement(label) {
|
||||
function makeElement(vm) {
|
||||
var label = vm[0];
|
||||
|
||||
var maxLineLength = _.max(label.split('\n'), function(l) { return l.length; }).length;
|
||||
|
||||
|
@ -171,83 +157,30 @@ mainApp.controller('homeCtrl', [ '$scope', 'Compute', '$rootScope', 'Loading','I
|
|||
// an approximation of the monospace font letter width.
|
||||
var width = 130;
|
||||
var height = 80;
|
||||
|
||||
/*return new joint.shapes.html.Element({
|
||||
id: label,
|
||||
name: label,
|
||||
size: { width: width, height: height },
|
||||
|
||||
html: [
|
||||
'<div class="html-element">',
|
||||
'<img src="./images/ON.png">',
|
||||
'<label></label>',
|
||||
'<input type="image" src="./images/gear.png" class="config"></button>',
|
||||
'</div>'
|
||||
].join(''),
|
||||
|
||||
attrs: {
|
||||
rect: {
|
||||
fill: '#FE854F',
|
||||
width: width,
|
||||
height: height,
|
||||
rx: 5,
|
||||
ry: 5,
|
||||
stroke: 'none'
|
||||
}
|
||||
}
|
||||
});*/
|
||||
return new joint.shapes.org.Member({
|
||||
id: label,
|
||||
position: { x: 0, y: 0 },
|
||||
attrs: {
|
||||
'.card': { fill: 'blue', stroke: 'none'},
|
||||
image: { 'xlink:href': './images/ON.png', opacity: 0.7 },
|
||||
//'.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
|
||||
'.name': { text: label, fill: 'white', 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
|
||||
var data = Compute.getData();
|
||||
console.log(data.machines[vm[1]]);
|
||||
if(data.machines[vm[1]].status == "ACTIVE"){
|
||||
return new joint.shapes.org.Member({
|
||||
id: vm[1],
|
||||
position: { x: 0, y: 0 },
|
||||
attrs: {
|
||||
'.card': { fill: 'blue', stroke: 'none'},
|
||||
image: { 'xlink:href': './images/ON.png', opacity: 0.7 },
|
||||
//'.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
|
||||
'.name': { text: label, fill: 'white', 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
|
||||
}
|
||||
});
|
||||
}else{
|
||||
return new joint.shapes.org.Member({
|
||||
id: vm[1],
|
||||
position: { x: 0, y: 0 },
|
||||
attrs: {
|
||||
'.card': { fill: 'blue', stroke: 'none'},
|
||||
image: { 'xlink:href': './images/OFF.png', opacity: 0.7 },
|
||||
//'.rank': { text: rank, fill: textColor, 'word-spacing': '-5px', 'letter-spacing': 0},
|
||||
'.name': { text: label, fill: 'white', 'font-size': 13, 'font-family': 'Arial', 'letter-spacing': 0 }
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var graph = new joint.dia.Graph;
|
||||
var paper = new joint.dia.Paper({
|
||||
el: $('#graphHolder'),
|
||||
width: $('#graphHolder').width(),
|
||||
//height: test.height,
|
||||
model: graph,
|
||||
gridSize: 1,
|
||||
interactive: false
|
||||
});
|
||||
paper.$el.css('pointer-events', 'none');
|
||||
var cells = buildGraphFromAdjacencyList(vmList);
|
||||
console.log(cells);
|
||||
/*graph.resetCells(cells);
|
||||
joint.layout.DirectedGraph.layout(graph, {
|
||||
setLinkVertices: false,
|
||||
//Top to bottom generation
|
||||
rankDir: "TB",
|
||||
nodeSep: 150,
|
||||
edgeSep: 150,
|
||||
rankSep: 150
|
||||
});*/
|
||||
graph.addCells(cells);
|
||||
var test = joint.layout.DirectedGraph.layout(graph, {
|
||||
setLinkVertices: false,
|
||||
//Top to bottom generation
|
||||
rankDir: "TB",
|
||||
nodeSep: 150,
|
||||
edgeSep: 150,
|
||||
rankSep: 50
|
||||
});
|
||||
console.log(test);
|
||||
|
||||
paper.setDimensions(test.width, test.height);
|
||||
|
||||
$(".Member").bind('click', function() {
|
||||
console.log("Click");
|
||||
$scope.raiseShowMachineDetailsEvent();
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}]);
|
||||
|
|
|
@ -3,41 +3,43 @@
|
|||
*
|
||||
* @param {$scope} $scope The $scope service from angular
|
||||
*/
|
||||
mainApp.controller('machineDetailsCtrl', [ '$scope', 'Compute', '$rootScope', '$timeout', function ($scope, Compute, $rootScope, $timeout)
|
||||
{
|
||||
|
||||
// Init scope
|
||||
$scope.machine={};
|
||||
$scope.machineIsStarting=false; // For loading icon
|
||||
mainApp.controller('machineDetailsCtrl', ['$scope', 'Compute', '$rootScope', '$timeout', 'Identity', function ($scope, Compute, $rootScope, $timeout, Identity)
|
||||
{
|
||||
|
||||
|
||||
$scope.$on('showMachineDetailsEvent', function(eventName ,machine, axioms){
|
||||
$scope.machine=machine;
|
||||
$scope.axioms=axioms;
|
||||
$('#machineDetailsModal').modal({backdrop: false, keyboard: true});
|
||||
});
|
||||
// Init scope
|
||||
$scope.machine = {};
|
||||
$scope.machineIsStarting = false; // For loading icon
|
||||
|
||||
// When we need to show details of machine
|
||||
$scope.$on('showMachineDetailsEvent', function (eventName, machine, axioms) {
|
||||
$scope.machine = machine;
|
||||
$scope.axioms = axioms;
|
||||
$('#machineDetailsModal').modal({backdrop: false, keyboard: true});
|
||||
});
|
||||
|
||||
// Try to stop or start a machine
|
||||
$scope.toggleMachineState = function () {
|
||||
// Display gif
|
||||
$scope.machineIsStarting = true;
|
||||
|
||||
// Fake timeout
|
||||
$timeout(function () {
|
||||
$scope.machineIsStarting = false;
|
||||
}, 3000);
|
||||
$timeout(function () {
|
||||
$scope.machine.online = !$scope.machine.online;
|
||||
|
||||
}, 3000);
|
||||
|
||||
|
||||
$scope.toggleMachineState=function(){
|
||||
// Display gif
|
||||
$scope.machineIsStarting=true;
|
||||
};
|
||||
|
||||
// Fake timeout
|
||||
$timeout(function(){
|
||||
$scope.machineIsStarting=false;
|
||||
}, 3000);
|
||||
$timeout(function(){
|
||||
$scope.machine.online=!$scope.machine.online;
|
||||
// Apply modifications
|
||||
$scope.applyModifications = function () {
|
||||
//Todo
|
||||
};
|
||||
|
||||
}, 3000);
|
||||
|
||||
|
||||
};
|
||||
|
||||
$scope.applyModifications=function(){
|
||||
//Todo
|
||||
}
|
||||
|
||||
|
||||
|
||||
}]);
|
||||
}]);
|
||||
|
|
|
@ -3,19 +3,22 @@
|
|||
*
|
||||
* @param {$scope} $scope The $scope service from angular
|
||||
*/
|
||||
mainApp.controller('imageCtrl', ['$scope', 'Image', 'Loading', function ($scope, Image, Loading)
|
||||
{
|
||||
var callbackTest=function(){
|
||||
$scope.images=Image.getData().images;
|
||||
Loading.stop();
|
||||
};
|
||||
mainApp.controller('imageCtrl', ['$scope', 'Image', 'Loading', 'Identity', function ($scope, Image, Loading, Identity)
|
||||
{
|
||||
|
||||
if(Image.getData().images==null){
|
||||
Loading.start();
|
||||
Image.getImages(callbackTest);
|
||||
}
|
||||
else{
|
||||
callbackTest();
|
||||
}
|
||||
|
||||
}]);
|
||||
// Update view
|
||||
var callMeAfterGetImage = function () {
|
||||
$scope.images = Image.getData().images;
|
||||
Loading.stop();
|
||||
};
|
||||
|
||||
// If user is login try to retrieve data
|
||||
if (Identity.isAlreadyLogin()) {
|
||||
if (Image.getData().images == null) {
|
||||
Loading.start();
|
||||
Image.getImages(callMeAfterGetImage);
|
||||
} else {
|
||||
callMeAfterGetImage();
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
|
62
client/js/controllers/image/upload.js
Normal file
62
client/js/controllers/image/upload.js
Normal file
|
@ -0,0 +1,62 @@
|
|||
/**
|
||||
* The image controller
|
||||
*
|
||||
* @param {$scope} $scope The $scope service from angular
|
||||
*/
|
||||
mainApp.controller('uploadImageCtrl', ['$scope', 'Image', 'Loading', 'Identity', 'upload', function ($scope, Image, Loading, Identity, upload)
|
||||
{
|
||||
/*$scope.uploader = new FileUploader({
|
||||
"token" : Identity.getToken(),
|
||||
"task" : "image",
|
||||
'action':'uploadImage',
|
||||
'id':'6564'
|
||||
});
|
||||
$scope.uploader.url='../server/index.php'
|
||||
$scope.uploader.alias='file_name'
|
||||
$scope.uploader.formData={
|
||||
"token" : Identity.getToken(),
|
||||
"task" : "image",
|
||||
'action':'uploadImage',
|
||||
'id':'6564'
|
||||
}
|
||||
*/
|
||||
|
||||
$scope.doUpload = function () {
|
||||
console.log($('#imageToUpload').prop('files')[0]);
|
||||
Image.uploadImage($('#imageToUpload').prop('files')[0], function () {
|
||||
alert("done")
|
||||
})
|
||||
/*$("#drop-area-div").dmUploader({
|
||||
extraData: {
|
||||
"token" : Identity.getToken(),
|
||||
"task" : "image",
|
||||
'action':'uploadImage',
|
||||
'id':'6564'},
|
||||
url:"../server/index.php"
|
||||
});
|
||||
*/
|
||||
|
||||
/*upload({
|
||||
url: '../server/index.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
"token" : Identity.getToken(),
|
||||
"task" : "image",
|
||||
'action':'uploadImage',
|
||||
'id':'6564',
|
||||
"file_name": $scope.myFile, // a jqLite type="file" element, upload() will extract all the files from the input and put them into the FormData object before sending.
|
||||
}
|
||||
}).then(
|
||||
function (response) {
|
||||
console.log(response.data); // will output whatever you choose to return from the server on a successful upload
|
||||
},
|
||||
function (response) {
|
||||
console.error(response); // Will return if status code is above 200 and lower than 300, same as $http
|
||||
}
|
||||
);*/
|
||||
|
||||
|
||||
};
|
||||
|
||||
$scope.token = Identity.getToken();
|
||||
}]);
|
|
@ -5,62 +5,63 @@
|
|||
* @param {$sce} $sce The $sce angular service
|
||||
* @param {$http} $http The $http angular service
|
||||
* @param {Identity} The Identity service
|
||||
|
||||
|
||||
*/
|
||||
mainApp.controller('loginCtrl', ['$scope','$sce','Identity', function ($scope,$sce, Identity)
|
||||
{
|
||||
// Check for login and define default states
|
||||
if(!Identity.isAlreadyLogin()){
|
||||
$('#loginModal').modal({backdrop: 'static', keyboard: false});
|
||||
}
|
||||
mainApp.controller('loginCtrl', ['$scope', '$sce', 'Identity', '$rootScope', function ($scope, $sce, Identity, $rootScope)
|
||||
{
|
||||
// Check for login and define default states
|
||||
if (!Identity.isAlreadyLogin()) {
|
||||
$('#loginModal').modal({backdrop: 'static', keyboard: false});
|
||||
}
|
||||
|
||||
// Manager logout event
|
||||
$scope.$on('logoutEvent', function(){
|
||||
$('#loginModal').modal({backdrop: 'static', keyboard: false});
|
||||
});
|
||||
// Manager logout event
|
||||
$scope.$on('logoutEvent', function () {
|
||||
$('#loginModal').modal({backdrop: 'static', keyboard: false});
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Hide loading button and message alert
|
||||
$('#loadingLoginButton').hide();
|
||||
$('#failedToLoginAlert').hide();
|
||||
|
||||
|
||||
// Defined function for login
|
||||
$scope.loginAction=function(){
|
||||
|
||||
// Begin login state for template
|
||||
$('#loginButton').hide();
|
||||
$('#loadingLoginButton').show();
|
||||
// Hide loading button and message alert
|
||||
$('#loadingLoginButton').hide();
|
||||
$('#failedToLoginAlert').hide();
|
||||
|
||||
// Get data from templates
|
||||
var username=$("#loginFormUsername").val();
|
||||
var password=$("#loginFormPassword").val();
|
||||
var projectname=$("#loginFormProjectname").val();
|
||||
|
||||
// Function to call to handle result
|
||||
var responseCallback=function(response){
|
||||
// Defined function for login
|
||||
$scope.loginAction = function () {
|
||||
|
||||
if(response.status!==0){
|
||||
// Set reason of fail
|
||||
$scope.failReason=response.failReason;
|
||||
// Begin login state for template
|
||||
$('#loginButton').hide();
|
||||
$('#loadingLoginButton').show();
|
||||
$('#failedToLoginAlert').hide();
|
||||
|
||||
// Display the error
|
||||
$('#failedToLoginAlert').show();
|
||||
}
|
||||
else {
|
||||
// Else the user is online !
|
||||
$('#loginModal').modal('hide');
|
||||
}
|
||||
// Get data from templates
|
||||
var username = $("#loginFormUsername").val();
|
||||
var password = $("#loginFormPassword").val();
|
||||
var projectname = $("#loginFormProjectname").val();
|
||||
|
||||
// Reset button state
|
||||
$('#loginButton').show();
|
||||
$('#loadingLoginButton').hide();
|
||||
}
|
||||
|
||||
// Try to login
|
||||
Identity.login(username, password, projectname, responseCallback);
|
||||
};
|
||||
|
||||
}]);
|
||||
// Function to call to handle result
|
||||
var responseCallback = function (response) {
|
||||
|
||||
if (response.status !== 0) {
|
||||
// Set reason of fail
|
||||
$scope.failReason = response.failReason;
|
||||
|
||||
// Display the error
|
||||
$('#failedToLoginAlert').show();
|
||||
} else {
|
||||
// Else the user is online !
|
||||
$('#loginModal').modal('hide');
|
||||
// Send login event
|
||||
$rootScope.$broadcast("loginEvent");
|
||||
}
|
||||
|
||||
// Reset button state
|
||||
$('#loginButton').show();
|
||||
$('#loadingLoginButton').hide();
|
||||
};
|
||||
|
||||
// Try to login
|
||||
Identity.login(username, password, projectname, responseCallback);
|
||||
};
|
||||
|
||||
}]);
|
||||
|
|
|
@ -5,4 +5,5 @@
|
|||
*/
|
||||
mainApp.controller('networkCtrl', function ($scope)
|
||||
{
|
||||
|
||||
});
|
|
@ -6,15 +6,14 @@
|
|||
* @param {$scope} $scope The $scope service from angular
|
||||
* @param {Identity} The Identity service
|
||||
*/
|
||||
mainApp.controller('statusCtrl', ['$scope','Identity', '$rootScope', function ($scope, Identity, $rootScope)
|
||||
{
|
||||
mainApp.controller('statusCtrl', ['$scope', 'Identity', '$rootScope', function ($scope, Identity, $rootScope)
|
||||
{
|
||||
// Give profile to model
|
||||
$scope.profile = Identity.getProfile();
|
||||
|
||||
// Give profile to model
|
||||
$scope.profile=Identity.getProfile();
|
||||
|
||||
// Function to logout
|
||||
$scope.logout=function(){
|
||||
Identity.logout();
|
||||
};
|
||||
// Function to logout
|
||||
$scope.logout = function () {
|
||||
Identity.logout();
|
||||
};
|
||||
|
||||
}]);
|
||||
}]);
|
||||
|
|
|
@ -1,141 +1,140 @@
|
|||
|
||||
mainApp.factory('Compute',[ '$http', 'Identity', function($http, Identity){
|
||||
mainApp.factory('Compute', ['$http', 'Identity', function ($http, Identity) {
|
||||
|
||||
|
||||
// Init data
|
||||
var data={};
|
||||
data.machines=null;
|
||||
data.axioms={} // Contain static data
|
||||
data.axioms.ram=[128,512,1024,2048,4096];
|
||||
data.axioms.disk=[1,2,5,10,25,50,100,150,200]
|
||||
data.axioms.images={}; // Retrieve after
|
||||
|
||||
|
||||
/**
|
||||
* Parse pullMachines answer
|
||||
* @param {response} the server response
|
||||
* @param {boolean} false if the request as been send true else
|
||||
* @return {requestParserResult} the result of parsing
|
||||
*/
|
||||
var parsePullMachinesAnswer=function(response, failedToSendRequest){
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult={};
|
||||
requestParserResult.status=1;
|
||||
requestParserResult.failReason=null;
|
||||
|
||||
|
||||
if (typeof response.data.Servers !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status=0;
|
||||
data.machines=response.data.Servers;
|
||||
|
||||
}
|
||||
else if(failedToSendRequest){
|
||||
requestParserResult.failReason="Failed to send request";
|
||||
}
|
||||
else{
|
||||
requestParserResult.failReason="Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
// Init data
|
||||
var data = {};
|
||||
data.machines = null;
|
||||
data.axioms = {} // Contain static data
|
||||
data.axioms.ram = [128, 512, 1024, 2048, 4096];
|
||||
data.axioms.disk = [1, 2, 5, 10, 25, 50, 100, 150, 200]
|
||||
data.axioms.images = {}; // Retrieve after
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve machine list
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullMachines=function(callback){
|
||||
// Send listServers request
|
||||
var result=$http.post('../server/index.php',
|
||||
$.param({"token" : Identity.getToken(), "task" : "compute", "action":"listServers"}));
|
||||
/**
|
||||
* Parse pullMachines answer
|
||||
* @param {response} the server response
|
||||
* @param {boolean} false if the request as been send true else
|
||||
* @return {requestParserResult} the result of parsing
|
||||
*/
|
||||
var parsePullMachinesAnswer = function (response, failedToSendRequest) {
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response){
|
||||
callback(parsePullMachinesAnswer(response, false));
|
||||
},function(response){
|
||||
callback(parsePullMachinesAnswer(response, true));
|
||||
});
|
||||
};
|
||||
// Defined return object
|
||||
var requestParserResult = {};
|
||||
requestParserResult.status = 1;
|
||||
requestParserResult.failReason = null;
|
||||
|
||||
|
||||
/**
|
||||
* Parse pullImages answer
|
||||
* @param {response} the server response
|
||||
* @param {boolean} false if the request as been send true else
|
||||
* @return {requestParserResult} the result of parsing
|
||||
*/
|
||||
var parsePullImagesAnswer=function(response, failedToSendRequest){
|
||||
if (typeof response.data.Servers !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status = 0;
|
||||
data.machines = response.data.Servers;
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult={};
|
||||
requestParserResult.status=1;
|
||||
requestParserResult.failReason=null;
|
||||
} else if (failedToSendRequest) {
|
||||
requestParserResult.failReason = "Failed to send PullMachine request";
|
||||
} else {
|
||||
requestParserResult.failReason = "Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
|
||||
|
||||
if (typeof response.data.Images !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status=0;
|
||||
data.axioms.images=response.data.Images;
|
||||
}
|
||||
else if(failedToSendRequest){
|
||||
requestParserResult.failReason="Failed to send request";
|
||||
}
|
||||
else{
|
||||
requestParserResult.failReason="Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve machine list
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullMachines = function (callback) {
|
||||
// Send listServers request
|
||||
var result = $http.post('../server/index.php',
|
||||
$.param({"token": Identity.getToken(), "task": "compute", "action": "listServers"}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response) {
|
||||
callback(parsePullMachinesAnswer(response, false));
|
||||
}, function (response) {
|
||||
callback(parsePullMachinesAnswer(response, true));
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Parse pullImages answer
|
||||
* @param {response} the server response
|
||||
* @param {boolean} false if the request as been send true else
|
||||
* @return {requestParserResult} the result of parsing
|
||||
*/
|
||||
var parsePullImagesAnswer = function (response, failedToSendRequest) {
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult = {};
|
||||
requestParserResult.status = 1;
|
||||
requestParserResult.failReason = null;
|
||||
|
||||
|
||||
if (typeof response.data.Images !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status = 0;
|
||||
data.axioms.images = response.data.Images;
|
||||
} else if (failedToSendRequest) {
|
||||
requestParserResult.failReason = "Failed to send PullImage request";
|
||||
} else {
|
||||
requestParserResult.failReason = "Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve machine list
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullImages=function(callback){
|
||||
// Send listServers request
|
||||
var result=$http.post('../server/index.php',
|
||||
$.param({"token" : Identity.getToken(), "task" : "compute", "action":"listImages"}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response){
|
||||
callback(parsePullImagesAnswer(response, false));
|
||||
},function(response){
|
||||
callback(parsePullImagesAnswer(response, true));
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Retrieve machine list
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullImages = function (callback) {
|
||||
// Send listServers request
|
||||
var result = $http.post('../server/index.php',
|
||||
$.param({"token": Identity.getToken(), "task": "compute", "action": "listImages"}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response) {
|
||||
callback(parsePullImagesAnswer(response, false));
|
||||
}, function (response) {
|
||||
|
||||
callback(parsePullImagesAnswer(response, true));
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve all data
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullData=function(callback){
|
||||
var nextFunction=function(response){
|
||||
if(response.status==0){
|
||||
pullMachines(callback);
|
||||
}
|
||||
}
|
||||
pullImages(nextFunction);
|
||||
}
|
||||
/**
|
||||
* Retrieve all data
|
||||
* @param {callback} function to call after request complete
|
||||
*/
|
||||
var pullData = function (callback) {
|
||||
var nextFunction = function (response) {
|
||||
if (response.status == 0) {
|
||||
pullMachines(callback);
|
||||
} else {
|
||||
callback(response);
|
||||
}
|
||||
};
|
||||
pullImages(nextFunction);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get Data
|
||||
* @return {data} return the data object
|
||||
*/
|
||||
var getData=function(){
|
||||
return data;
|
||||
}
|
||||
|
||||
// Return services objects
|
||||
return {
|
||||
pullMachines: pullMachines,
|
||||
pullData: pullData,
|
||||
getData: getData
|
||||
};
|
||||
/**
|
||||
* Get Data
|
||||
* @return {data} return the data object
|
||||
*/
|
||||
var getData = function () {
|
||||
return data;
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
// Return services objects
|
||||
return {
|
||||
pullMachines: pullMachines,
|
||||
pullData: pullData,
|
||||
getData: getData
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
|
|
|
@ -1,163 +1,168 @@
|
|||
|
||||
mainApp.factory('Identity',[ '$http', '$cookies', function($http, $cookies){
|
||||
mainApp.factory('Identity', ['$http', '$cookies', '$rootScope', function ($http, $cookies, $rootScope) {
|
||||
|
||||
/* Create profile structure to store informations
|
||||
* about current session
|
||||
*/
|
||||
var profile={};
|
||||
profile.username=null;
|
||||
profile.projectname=null;
|
||||
var token=null;
|
||||
|
||||
|
||||
/*
|
||||
* @returns {boolean} Return true if a cookie is found (and load it in profile) false else
|
||||
*/
|
||||
var isAlreadyLogin=function(){
|
||||
|
||||
// Load cookies
|
||||
var profileInCookie=$cookies.getObject('profile');
|
||||
var tokenPart_0InCookie=$cookies.getObject('token.part_0');
|
||||
var tokenPart_1InCookie=$cookies.getObject('token.part_1');
|
||||
|
||||
|
||||
// Check if cookie is defined
|
||||
if(typeof profileInCookie !== 'undefined'
|
||||
&& typeof tokenPart_0InCookie !== 'undefined'
|
||||
&& typeof tokenPart_1InCookie !== 'undefined'
|
||||
){
|
||||
|
||||
// If yes, put it into variables
|
||||
angular.extend(profile, profileInCookie);
|
||||
token=tokenPart_0InCookie+tokenPart_1InCookie;
|
||||
|
||||
// Return I'm Login
|
||||
return true;
|
||||
}
|
||||
|
||||
// Return I'm not Login
|
||||
return false;
|
||||
}
|
||||
/* Create profile structure to store informations
|
||||
* about current session
|
||||
*/
|
||||
var profile = {};
|
||||
profile.username = null;
|
||||
profile.projectname = null;
|
||||
var token = null;
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* Destroy profile cookies
|
||||
*/
|
||||
var logout=function(){
|
||||
$cookies.remove('profile');
|
||||
$cookies.remove('token.part_0');
|
||||
$cookies.remove('token.part_1');
|
||||
token=null;
|
||||
profile.username=null;
|
||||
profile.projectname=null;
|
||||
/*
|
||||
* @returns {boolean} Return true if a cookie is found (and load it in profile) false else
|
||||
*/
|
||||
var isAlreadyLogin = function () {
|
||||
|
||||
// Reload Page
|
||||
location.reload();
|
||||
}
|
||||
// Load cookies
|
||||
var profileInCookie = $cookies.getObject('profile');
|
||||
var tokenPart_0InCookie = $cookies.getObject('token.part_0');
|
||||
var tokenPart_1InCookie = $cookies.getObject('token.part_1');
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} response The response to parse
|
||||
* @param {boolean} to check if the request is send or not
|
||||
* @returns {requestParserResult} Formated data
|
||||
*/
|
||||
var parseLoginAnswer=function(response, failedToSendRequest){
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult={};
|
||||
requestParserResult.status=1;
|
||||
requestParserResult.failReason=null;
|
||||
|
||||
if (typeof response.data.token !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status=0;
|
||||
// Check if cookie is defined
|
||||
if (typeof profileInCookie !== 'undefined'
|
||||
&& typeof tokenPart_0InCookie !== 'undefined'
|
||||
&& typeof tokenPart_1InCookie !== 'undefined'
|
||||
) {
|
||||
|
||||
// Find the middle of the token to split it
|
||||
var middle=parseInt(response.data.token.length/2);
|
||||
//if(token!==null){
|
||||
// If yes, put it into variables
|
||||
angular.extend(profile, profileInCookie);
|
||||
token = tokenPart_0InCookie + tokenPart_1InCookie;
|
||||
//}
|
||||
|
||||
// Create expire date (cookie expire in 55 mins)
|
||||
var expireDate=new Date();
|
||||
expireDate.setMinutes(expireDate.getMinutes()+55);
|
||||
|
||||
// Save profile
|
||||
$cookies.putObject('profile', profile, {'expires': expireDate});
|
||||
// Save first part of token
|
||||
$cookies.putObject('token.part_0', response.data.token.substring(0, middle), {'expires': expireDate});
|
||||
// Save second part of token
|
||||
$cookies.putObject('token.part_1', response.data.token.substring(middle, response.data.token.length), {'expires': expireDate});
|
||||
// Return I'm Login
|
||||
return true;
|
||||
}
|
||||
|
||||
// Put token in var
|
||||
token=response.data.token;
|
||||
|
||||
}
|
||||
else if(failedToSendRequest){
|
||||
requestParserResult.failReason="Failed to send request";
|
||||
}
|
||||
else{
|
||||
requestParserResult.failReason="Please check your username, password and project name !";
|
||||
}
|
||||
// Show the login overlay
|
||||
$rootScope.$broadcast("logoutEvent");
|
||||
|
||||
|
||||
return requestParserResult;
|
||||
};
|
||||
// Return I'm not Login
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Function to connect to OpenStack
|
||||
*
|
||||
* @param {object} $http Angular $http service
|
||||
* @param {string} username The user name
|
||||
* @param {string} password The user password
|
||||
* @param {string} projectname The user project name
|
||||
* @param {function} function to call when data is avalaible
|
||||
*/
|
||||
var login=function(username, password,projectname,callback){
|
||||
|
||||
// Set profile information (early)
|
||||
profile.username=username;
|
||||
profile.projectname=projectname;
|
||||
|
||||
var result=$http.post('../server/index.php',
|
||||
$.param({"task" : "Authenticate", "user" : username, "password" : password, "project" : projectname}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response){
|
||||
callback(parseLoginAnswer(response, false));
|
||||
},function(response){
|
||||
callback(parseLoginAnswer(response, true));
|
||||
});
|
||||
};
|
||||
|
||||
/*
|
||||
* Destroy profile cookies
|
||||
*/
|
||||
var logout = function () {
|
||||
$cookies.remove('profile');
|
||||
$cookies.remove('token.part_0');
|
||||
$cookies.remove('token.part_1');
|
||||
token = null;
|
||||
profile.username = null;
|
||||
profile.projectname = null;
|
||||
|
||||
// Reload Page
|
||||
//location.reload();
|
||||
$rootScope.$broadcast("logoutEvent");
|
||||
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} response The response to parse
|
||||
* @param {boolean} to check if the request is send or not
|
||||
* @returns {requestParserResult} Formated data
|
||||
*/
|
||||
var parseLoginAnswer = function (response, failedToSendRequest) {
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult = {};
|
||||
requestParserResult.status = 1;
|
||||
requestParserResult.failReason = null;
|
||||
|
||||
if (typeof response.data.token !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status = 0;
|
||||
|
||||
// Find the middle of the token to split it
|
||||
var middle = parseInt(response.data.token.length / 2);
|
||||
|
||||
// Create expire date (cookie expire in 55 mins)
|
||||
var expireDate = new Date();
|
||||
expireDate.setMinutes(expireDate.getMinutes() + 55);
|
||||
|
||||
// Save profile
|
||||
$cookies.putObject('profile', profile, {'expires': expireDate});
|
||||
// Save first part of token
|
||||
$cookies.putObject('token.part_0', response.data.token.substring(0, middle), {'expires': expireDate});
|
||||
// Save second part of token
|
||||
$cookies.putObject('token.part_1', response.data.token.substring(middle, response.data.token.length), {'expires': expireDate});
|
||||
|
||||
// Put token in var
|
||||
token = response.data.token;
|
||||
|
||||
} else if (failedToSendRequest) {
|
||||
requestParserResult.failReason = "Failed to send request";
|
||||
} else {
|
||||
requestParserResult.failReason = "Please check your username, password and project name !";
|
||||
}
|
||||
|
||||
|
||||
return requestParserResult;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Function to connect to OpenStack
|
||||
*
|
||||
* @param {object} $http Angular $http service
|
||||
* @param {string} username The user name
|
||||
* @param {string} password The user password
|
||||
* @param {string} projectname The user project name
|
||||
* @param {function} function to call when data is avalaible
|
||||
*/
|
||||
var login = function (username, password, projectname, callback) {
|
||||
|
||||
// Set profile information (early)
|
||||
profile.username = username;
|
||||
profile.projectname = projectname;
|
||||
|
||||
var result = $http.post('../server/index.php',
|
||||
$.param({"task": "Authenticate", "user": username, "password": password, "project": projectname}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response) {
|
||||
callback(parseLoginAnswer(response, false));
|
||||
}, function (response) {
|
||||
callback(parseLoginAnswer(response, true));
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* Get the profile
|
||||
*/
|
||||
var getProfile=function(){
|
||||
return profile;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the token
|
||||
*/
|
||||
var getToken=function(){
|
||||
return token;
|
||||
}
|
||||
/*
|
||||
* Get the profile
|
||||
*/
|
||||
var getProfile = function () {
|
||||
return profile;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* Get the token
|
||||
*/
|
||||
var getToken = function () {
|
||||
return token;
|
||||
};
|
||||
|
||||
// Return services objects
|
||||
return {
|
||||
login: login,
|
||||
getProfile: getProfile,
|
||||
isAlreadyLogin: isAlreadyLogin,
|
||||
logout:logout,
|
||||
getToken:getToken
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
|
||||
// Return services objects
|
||||
return {
|
||||
login: login,
|
||||
getProfile: getProfile,
|
||||
isAlreadyLogin: isAlreadyLogin,
|
||||
logout: logout,
|
||||
getToken: getToken
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
|
|
|
@ -1,59 +1,114 @@
|
|||
|
||||
mainApp.factory('Image',[ '$http', 'Identity', function($http, Identity){
|
||||
mainApp.factory('Image', ['$http', 'Identity', function ($http, Identity) {
|
||||
|
||||
var data={};
|
||||
data.images=null;
|
||||
// Data object
|
||||
var data = {};
|
||||
data.images = null; // Images
|
||||
|
||||
/**
|
||||
* Parse uploadImage anwser
|
||||
* @param {type} response
|
||||
* @param {type} failedToSendRequest
|
||||
* @returns {Image_L2.parseUploadImageAnswer.requestParserResult}
|
||||
*/
|
||||
var parseUploadImageAnswer = function (response, failedToSendRequest) {
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult = {};
|
||||
requestParserResult.status = 1;
|
||||
requestParserResult.failReason = null;
|
||||
|
||||
|
||||
var parseUploadImageAnswer=function(response, failedToSendRequest){
|
||||
if (typeof response.data.Images !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status = 0;
|
||||
data.images = response.data.Images;
|
||||
|
||||
// Defined return object
|
||||
var requestParserResult={};
|
||||
requestParserResult.status=1;
|
||||
requestParserResult.failReason=null;
|
||||
|
||||
|
||||
if (typeof response.data.Images !== 'undefined') {
|
||||
// Set status code
|
||||
requestParserResult.status=0;
|
||||
data.images=response.data.Images;
|
||||
|
||||
}
|
||||
else if(failedToSendRequest){
|
||||
requestParserResult.failReason="Failed to send request";
|
||||
}
|
||||
else{
|
||||
requestParserResult.failReason="Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
} else if (failedToSendRequest) {
|
||||
requestParserResult.failReason = "Failed to send request";
|
||||
} else {
|
||||
requestParserResult.failReason = "Error";
|
||||
}
|
||||
return requestParserResult;
|
||||
};
|
||||
|
||||
|
||||
var getImages=function(callback){
|
||||
/**
|
||||
* Get images
|
||||
* @param {type} callback
|
||||
* @returns {undefined}
|
||||
*/
|
||||
var getImages = function (callback) {
|
||||
|
||||
var result=$http.post('../server/index.php',
|
||||
$.param({"token" : Identity.getToken(), "task" : "image", 'action':'listImage'}));
|
||||
var result = $http.post('../server/index.php',
|
||||
$.param({"token": Identity.getToken(), "task": "image", 'action': 'listImage'}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response){
|
||||
callback(parseUploadImageAnswer(response, false));
|
||||
},function(response){
|
||||
callback(parseUploadImageAnswer(response, true));
|
||||
});
|
||||
|
||||
|
||||
};
|
||||
// Wait and handle the response
|
||||
result.then(function (response) {
|
||||
callback(parseUploadImageAnswer(response, false));
|
||||
}, function (response) {
|
||||
callback(parseUploadImageAnswer(response, true));
|
||||
});
|
||||
|
||||
|
||||
var getData=function(response){
|
||||
return data;
|
||||
};
|
||||
|
||||
// Return services objects
|
||||
return {
|
||||
getImages:getImages,
|
||||
getData:getData
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
/**
|
||||
* Upload an image
|
||||
* @param {type} fileToUpload
|
||||
* @param {type} callback
|
||||
* @returns {undefined}
|
||||
*/
|
||||
var uploadImage = function (fileToUpload, callback) {
|
||||
var form_data = new FormData();
|
||||
form_data.append('file', fileToUpload);
|
||||
console.log(fileToUpload);
|
||||
form_data.append("task", "image");
|
||||
form_data.append("token", Identity.getToken());
|
||||
form_data.append('action', "uploadImage");
|
||||
form_data.append('id', '6564');
|
||||
form_data.append('file_name', fileToUpload);
|
||||
|
||||
$.ajax({
|
||||
url: "../server/index.php", // Url to which the request is send
|
||||
type: "POST", // Type of request to be send, called as method
|
||||
data: form_data, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
|
||||
file_name: fileToUpload,
|
||||
token: Identity.getToken(),
|
||||
task: "image",
|
||||
action: 'uploadImage',
|
||||
id: '6564',
|
||||
contentType: false, // The content type used when sending data to the server.
|
||||
cache: false, // To unable request pages to be cached
|
||||
processData: false, // To send DOMDocument or non processed data file it is set to false
|
||||
success: function (data) // A function to be called if request succeeds
|
||||
{
|
||||
alert("success");
|
||||
}
|
||||
});
|
||||
|
||||
//var result=$http.post('../server/index.php',
|
||||
// $.param({"token" : Identity.getToken(), "task" : "image", 'action':'uploadImage', 'file_name':form_data, 'id':'6564'}));
|
||||
|
||||
// Wait and handle the response
|
||||
/* result.then(function (response){
|
||||
callback(parseUploadImageAnswer(response, false));
|
||||
},function(response){
|
||||
callback(parseUploadImageAnswer(response, true));
|
||||
});*/
|
||||
};
|
||||
|
||||
|
||||
var getData = function (response) {
|
||||
return data;
|
||||
};
|
||||
|
||||
// Return services objects
|
||||
return {
|
||||
getImages: getImages,
|
||||
getData: getData,
|
||||
uploadImage: uploadImage
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
|
|
|
@ -1,23 +1,26 @@
|
|||
/**
|
||||
* Loading service
|
||||
* @param {type} param1
|
||||
* @param {type} param2
|
||||
*/
|
||||
mainApp.factory('Loading', [function () {
|
||||
/**
|
||||
* Display Loading modal
|
||||
*/
|
||||
var start = function () {
|
||||
$('#loadingModal').modal({backdrop: 'static', keyboard: false});
|
||||
};
|
||||
|
||||
mainApp.factory('Loading',[ function(){
|
||||
/**
|
||||
* Display Loading modal
|
||||
*/
|
||||
var start=function(){
|
||||
$('#loadingModal').modal({backdrop: 'static', keyboard: false});
|
||||
};
|
||||
/**
|
||||
* Hide Loading modal
|
||||
*/
|
||||
var stop = function () {
|
||||
$('#loadingModal').modal('hide');
|
||||
};
|
||||
|
||||
/**
|
||||
* Hide Loading modal
|
||||
*/
|
||||
var stop=function(){
|
||||
$('#loadingModal').modal('hide');
|
||||
}
|
||||
|
||||
|
||||
// Service returns
|
||||
return {
|
||||
start:start,
|
||||
stop:stop
|
||||
};
|
||||
}]);
|
||||
// Service returns
|
||||
return {
|
||||
start: start,
|
||||
stop: stop
|
||||
};
|
||||
}]);
|
||||
|
|
29
client/js/services/Network.js
Normal file
29
client/js/services/Network.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
|
||||
mainApp.factory('Network', ['$http', 'Identity', function ($http, Identity) {
|
||||
|
||||
// Data object
|
||||
var data = {};
|
||||
data.networks = null; // Networks
|
||||
|
||||
/**
|
||||
* ListId
|
||||
* @param {type} fileToUpload
|
||||
* @param {type} callback
|
||||
* @returns {undefined}
|
||||
*/
|
||||
var ListId = function (fileToUpload, callback) {
|
||||
var result = $http.post('../server/index.php',
|
||||
$.param({"token": Identity.getToken(), "task": "network", 'action': 'list_network_ids'}));
|
||||
|
||||
// Wait and handle the response
|
||||
result.then(function (response) {
|
||||
callback(parseUploadImageAnswer(response, false));
|
||||
}, function (response) {
|
||||
callback(parseUploadImageAnswer(response, true));
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
}]);
|
||||
|
||||
|
8
client/js/services/Test.js
Normal file
8
client/js/services/Test.js
Normal file
|
@ -0,0 +1,8 @@
|
|||
var app = angular.module('mainApp',[]);
|
||||
app.controller('hassan', function($scope,$http){
|
||||
$http.get('http://127.0.0.1/database.json').success(function(response){
|
||||
$scope.persons = response.records;
|
||||
});
|
||||
|
||||
|
||||
});
|
8
client/partials/home/home.html
Normal file → Executable file
8
client/partials/home/home.html
Normal file → Executable file
|
@ -1,11 +1,11 @@
|
|||
<div class="panel panel-default">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
Home
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
|
||||
<div id="graphHolder"></div>
|
||||
Pour charger les machines, recharger la page (temporaire)<br />
|
||||
Selectionner une machine:
|
||||
<div ng-repeat="machine in machines"> <a ng-click="raiseShowMachineDetailsEvent(machine.id)"> {{ machine.name }}</a></div>
|
||||
Selectionner une machine:
|
||||
<div ng-repeat="machine in machines"> <a ng-click="raiseShowMachineDetailsEvent(machine.id)"> {{ machine.name }}</a></div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -1,10 +1,38 @@
|
|||
<div class="panel panel-default" ng-controller="imageCtrl">
|
||||
|
||||
|
||||
<div class="panel panel-default" ng-controller="imageCtrl">
|
||||
<div class="panel-heading">
|
||||
Images disponibles
|
||||
Image Manager
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div ng-repeat="image in images">
|
||||
{{image.name}}
|
||||
|
||||
|
||||
<div class="btn-group btn-group-md" role="group" aria-label="...">
|
||||
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#uploadImageModal"">Upload</button>
|
||||
<button type="button" class="btn btn-default">Download</button>
|
||||
</div>
|
||||
<p></p>
|
||||
<table class="table table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Size</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr ng-repeat="image in images">
|
||||
<td>{{ image.name }}</td>
|
||||
<td>{{ (image.size / 1048576).toFixed(2) }} MB</td>
|
||||
<td><button type="button" class="btn btn-danger">Remove</button></td>
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
|
31
client/partials/image/upload.html
Normal file
31
client/partials/image/upload.html
Normal file
|
@ -0,0 +1,31 @@
|
|||
<div class="modal fade" id="uploadImageModal" ng-controller="uploadImageCtrl">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content"></div>
|
||||
</div>
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<!--<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>-->
|
||||
<h4 class="modal-title">Upload Image</h4>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
|
||||
<form action="../server/index.php" method="post">
|
||||
<input type="hidden" name="task" value="image" />
|
||||
<input type="hidden" name="token" value="{{ token }}" />
|
||||
<input type="hidden" name="action" value="uploadImage" />
|
||||
<input type="hidden" name="id" value="2564" />
|
||||
<input name="file" type="file" />
|
||||
<input type="submit" value="Upload" />
|
||||
</form>
|
||||
|
||||
<div class="modal-footer">
|
||||
<!--<a href="#" data-dismiss="modal" class="btn btn-default">Close</a>-->
|
||||
|
||||
<a class="btn btn-lg btn-primary btn-block" id="loginButton" ng-click="doUpload()">Upload</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
7
client/vendors/angularjs/angular-file-upload.min.js
vendored
Normal file
7
client/vendors/angularjs/angular-file-upload.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
client/vendors/angularjs/angular-upload.min.js
vendored
Normal file
1
client/vendors/angularjs/angular-upload.min.js
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
"use strict";angular.module("lr.upload",["lr.upload.formdata","lr.upload.iframe","lr.upload.directives"]),angular.module("lr.upload.directives",[]),angular.module("lr.upload.directives").directive("uploadButton",["upload",function(a){return{restrict:"EA",scope:{data:"=?data",url:"@",id:"@",param:"@",method:"@",onUpload:"&",onSuccess:"&",onError:"&",onComplete:"&"},link:function(b,c,d){var e=angular.element(c),f=angular.element('<input id="'+b.id+'" type="file" />');if(e.append(f),f.on("change",function(){var c=angular.element(this);if(!c[0].files||0!==c[0].files.length){var e={url:b.url,method:b.method||"POST",forceIFrameUpload:b.$eval(d.forceIframeUpload)||!1,data:b.data||{}};e.data[b.param||"file"]=c,b.$apply(function(){b.onUpload({files:c[0].files})}),a(e).then(function(a){b.onSuccess({response:a}),b.onComplete({response:a})},function(a){b.onError({response:a}),b.onComplete({response:a})})}}),"required"in d&&d.$observe("required",function(a){var d=""===a?!0:b.$eval(a);f.attr("required",d),c.toggleClass("ng-valid",!d),c.toggleClass("ng-invalid ng-invalid-required",d)}),"accept"in d&&d.$observe("accept",function(a){f.attr("accept",a)}),a.support.formData){var g=function(){f.attr("multiple",!(!b.$eval(d.multiple)||b.$eval(d.forceIframeUpload)))};d.$observe("multiple",g),d.$observe("forceIframeUpload",g)}}}}]),angular.module("lr.upload.formdata",[]).factory("formDataTransform",function(){return function(a){var b=new FormData;return angular.forEach(a,function(a,c){if(angular.isElement(a)){var d=[];angular.forEach(a,function(a){angular.forEach(a.files,function(a){d.push(a)}),a.value=""}),0!==d.length&&(d.length>1?angular.forEach(d,function(a,d){b.append(c+"["+d+"]",a)}):b.append(c,d[0]))}else b.append(c,a)}),b}}).factory("formDataUpload",["$http","formDataTransform",function(a,b){return function(c){return c.transformRequest=b,c.method=c.method||"POST",c.headers=angular.extend(c.headers||{},{"Content-Type":void 0}),a(c)}}]),angular.module("lr.upload.iframe",[]).factory("iFrameUpload",["$q","$http","$document","$rootScope",function(a,b,c,d){function e(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;c++)if(b===a[c])return c;return-1}function f(f){var g=[],h=a.defer(),i=h.promise;angular.forEach(f.data||{},function(a,b){angular.isElement(a)&&(delete f.data[b],a.attr("name",b),g.push(a))});var j=/\?/.test(f.url)?"&":"?";"DELETE"===f.method?(f.url=f.url+j+"_method=DELETE",f.method="POST"):"PUT"===f.method?(f.url=f.url+j+"_method=PUT",f.method="POST"):"PATCH"===f.method&&(f.url=f.url+j+"_method=PATCH",f.method="POST");var k=angular.element(c[0].body),l=d.$new(),m="iframe-transport-"+l.$id;l.$destroy();var n=angular.element("<form></form>");n.attr("target",m),n.attr("action",f.url),n.attr("method",f.method||"POST"),n.css("display","none"),g.length&&(n.attr("enctype","multipart/form-data"),n.attr("encoding","multipart/form-data"));var o=angular.element('<iframe name="'+m+'" src="javascript:false;"></iframe>');return o.on("load",function(){function a(a,b){var c=[];return angular.isFunction(b)?b(a,c):(angular.forEach(b,function(b){a=b(a,c)}),a)}function c(){var a=e(b.pendingRequests,f);-1!==a&&(b.pendingRequests.splice(a,1),f.$iframeTransportForm.remove(),delete f.$iframeTransportForm)}o.off("load").on("load",function(){var c;try{var d=this.contentWindow?this.contentWindow.document:this.contentDocument;if(c=angular.element(d.body).text(),!c.length)throw new Error}catch(e){}n.append(angular.element('<iframe src="javascript:false;"></iframe>'));try{c=a(c,b.defaults.transformResponse)}catch(e){}h.resolve({data:c,status:200,headers:[],config:f})}),angular.forEach(f.data,function(a,b){var c=angular.element('<input type="hidden" />');c.attr("name",b),c.val(a),n.append(c)}),angular.forEach(g,function(a){var b=a.clone(!0);a.after(b),n.append(a)}),f.$iframeTransportForm=n,b.pendingRequests.push(f),n[0].submit(),i.then(c,c)}),n.append(o),k.append(n),i}return f}]),angular.module("lr.upload").factory("upload",["$window","formDataUpload","iFrameUpload",function(a,b,c){function d(a){return e.formData&&!a.forceIFrameUpload?b(a):c(a)}var e={fileInput:!(new RegExp("(Android (1\\.[0156]|2\\.[01]))|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)|(w(eb)?OSBrowser)|(webOS)|(Kindle/(1\\.0|2\\.[05]|3\\.0))").test(a.navigator.userAgent)||angular.element('<input type="file">').prop("disabled")),fileUpload:!(!a.XMLHttpRequestUpload||!a.FileReader),formData:!!a.FormData};return d.support=e,d}]);
|
9
client/vendors/jquery/dmuploader.min.js
vendored
Normal file
9
client/vendors/jquery/dmuploader.min.js
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
/*
|
||||
* dmuploader.min.js - Jquery File Uploader - 0.1
|
||||
* http://www.daniel.com.uy/projects/jquery-file-uploader/
|
||||
*
|
||||
* Copyright (c) 2013 Daniel Morales
|
||||
* Dual licensed under the MIT and GPL licenses.
|
||||
* http://www.daniel.com.uy/doc/license/
|
||||
*/
|
||||
(function(t){var n="dmUploader";var r={url:document.URL,method:"POST",extraData:{},maxFileSize:0,allowedTypes:"*",extFilter:null,dataType:null,fileName:"file",onInit:function(){},onFallbackMode:function(){message},onNewFile:function(e,t){},onBeforeUpload:function(e){},onComplete:function(){},onUploadProgress:function(e,t){},onUploadSuccess:function(e,t){},onUploadError:function(e,t){},onFileTypeError:function(e){},onFileSizeError:function(e){},onFileExtError:function(e){}};var i=function(e,n){this.element=t(e);this.settings=t.extend({},r,n);if(!this.checkBrowser()){return false}this.init();return true};i.prototype.checkBrowser=function(){if(window.FormData===undefined){this.settings.onFallbackMode.call(this.element,"Browser doesn't support Form API");return false}if(this.element.find("input[type=file]").length>0){return true}if(!this.checkEvent("drop",this.element)||!this.checkEvent("dragstart",this.element)){this.settings.onFallbackMode.call(this.element,"Browser doesn't support Ajax Drag and Drop");return false}return true};i.prototype.checkEvent=function(e,t){var t=t||document.createElement("div");var e="on"+e;var n=e in t;if(!n){if(!t.setAttribute){t=document.createElement("div")}if(t.setAttribute&&t.removeAttribute){t.setAttribute(e,"");n=typeof t[e]=="function";if(typeof t[e]!="undefined"){t[e]=undefined}t.removeAttribute(e)}}t=null;return n};i.prototype.init=function(){var e=this;e.queue=new Array;e.queuePos=-1;e.queueRunning=false;e.element.on("drop",function(t){t.preventDefault();var n=t.originalEvent.dataTransfer.files;e.queueFiles(n)});e.element.find("input[type=file]").on("change",function(n){var r=n.target.files;e.queueFiles(r);t(this).val("")});this.settings.onInit.call(this.element)};i.prototype.queueFiles=function(e){var n=this.queue.length;for(var r=0;r<e.length;r++){var i=e[r];if(this.settings.maxFileSize>0&&i.size>this.settings.maxFileSize){this.settings.onFileSizeError.call(this.element,i);continue}if(this.settings.allowedTypes!="*"&&!i.type.match(this.settings.allowedTypes)){this.settings.onFileTypeError.call(this.element,i);continue}if(this.settings.extFilter!=null){var s=this.settings.extFilter.toLowerCase().split(";");var o=i.name.toLowerCase().split(".").pop();if(t.inArray(o,s)<0){this.settings.onFileExtError.call(this.element,i);continue}}this.queue.push(i);var u=this.queue.length-1;this.settings.onNewFile.call(this.element,u,i)}if(this.queueRunning){return false}if(this.queue.length==n){return false}this.processQueue();return true};i.prototype.processQueue=function(){var n=this;n.queuePos++;if(n.queuePos>=n.queue.length){n.settings.onComplete.call(n.element);n.queuePos=n.queue.length-1;n.queueRunning=false;return}var r=n.queue[n.queuePos];var i=new FormData;i.append(n.settings.fileName,r);n.settings.onBeforeUpload.call(n.element,n.queuePos);t.each(n.settings.extraData,function(e,t){i.append(e,t)});n.queueRunning=true;t.ajax({url:n.settings.url,type:n.settings.method,dataType:n.settings.dataType,data:i,cache:false,contentType:false,processData:false,forceSync:false,xhr:function(){var r=t.ajaxSettings.xhr();if(r.upload){r.upload.addEventListener("progress",function(t){var r=0;var i=t.loaded||t.position;var s=t.total||e.totalSize;if(t.lengthComputable){r=Math.ceil(i/s*100)}n.settings.onUploadProgress.call(n.element,n.queuePos,r)},false)}return r},success:function(e,t,r){n.settings.onUploadSuccess.call(n.element,n.queuePos,e)},error:function(e,t,r){n.settings.onUploadError.call(n.element,n.queuePos,r)},complete:function(e,t){n.processQueue()}})};t.fn.dmUploader=function(e){return this.each(function(){if(!t.data(this,n)){t.data(this,n,new i(this,e))}})};t(document).on("dragenter",function(e){e.stopPropagation();e.preventDefault()});t(document).on("dragover",function(e){e.stopPropagation();e.preventDefault()});t(document).on("drop",function(e){e.stopPropagation();e.preventDefault()})})(jQuery)
|
|
@ -0,0 +1,3 @@
|
|||
<?php
|
||||
phpinfo();
|
||||
?>
|
2
server/.gitignore
vendored
Normal file
2
server/.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
vendor/*
|
||||
composer.lock
|
0
server/Readme.md
Normal file → Executable file
0
server/Readme.md
Normal file → Executable file
|
@ -1,24 +1,12 @@
|
|||
<?php
|
||||
include_once("../core/Plugin_Api.php");
|
||||
include_once("../core/LibOverride/genTokenOptions.php");
|
||||
<<<<<<< HEAD
|
||||
<<<<<<< Updated upstream
|
||||
=======
|
||||
include_once("../core/ErrorManagement.php");
|
||||
|
||||
use OpenCloud\Common\Error\BadResponseError;
|
||||
use OpenCloud\Common\Error\BaseError;
|
||||
use OpenCloud\Common\Error\NotImplementedError;
|
||||
use OpenCloud\Common\Error\UserInputError;
|
||||
>>>>>>> Stashed changes
|
||||
=======
|
||||
include_once("../core/ErrorManagement.php");
|
||||
|
||||
use OpenStack\Common\Error\BadResponseError;
|
||||
use OpenStack\Common\Error\BaseError;
|
||||
use OpenStack\Common\Error\NotImplementedError;
|
||||
use OpenStack\Common\Error\UserInputError;
|
||||
>>>>>>> develop
|
||||
|
||||
class AppTest{
|
||||
|
||||
|
@ -34,7 +22,7 @@ class AppTest{
|
|||
|
||||
$this->tokenPost = NULL;
|
||||
$this->tokenClass = new genTokenOptions($args);
|
||||
$this->openstack = new OpenStack\OpenStack([]);
|
||||
$this->openstack = new OpenStack\OpenStack(['authUrl' => $args["authUrl"]]);
|
||||
$this->pluginsApi = plugin_api::getInstance();
|
||||
$this->errorClass = new errorManagement($this);
|
||||
$this->output = array();
|
||||
|
@ -75,6 +63,11 @@ class AppTest{
|
|||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->networkingV2($opt);
|
||||
break;
|
||||
case "NetworkLayer3":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genNetworkToken();
|
||||
$opt = $this->tokenClass->getOptions('Network');
|
||||
return $this->openstack->networkingV2ExtLayer3($opt);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -101,9 +94,17 @@ class AppTest{
|
|||
}
|
||||
|
||||
public function getPostParam($name){
|
||||
if(isset($this->postParams[$name])){
|
||||
return $this->postParams[$name];
|
||||
}else{
|
||||
$this->setOutput("Error", "Missing parameter ".$name);
|
||||
}
|
||||
}
|
||||
|
||||
public function setPostParam($name, $value){
|
||||
|
||||
return $this->postParams[$name];
|
||||
|
||||
$this->postParams[$name] = $value;
|
||||
|
||||
}
|
||||
|
||||
public function setOutput($key, $out){
|
||||
|
|
26
server/Test/DisplayListCidr.php
Executable file
26
server/Test/DisplayListCidr.php
Executable file
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
ini_set('display_errors', 1);
|
||||
date_default_timezone_set("Europe/Paris");
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
$options = Array();
|
||||
$options["user"] = Array("name"=>"admin", "password"=>"ae5or6cn", "domain"=>["id"=>"Default"]);
|
||||
$options["scope"] = Array("project"=>Array("name"=>"admin", "domain"=>["id"=>"Default"]));
|
||||
$options["authUrl"] = "http://148.60.11.31:5000/v3";
|
||||
$openstack = new OpenStack\OpenStack($options);
|
||||
$networking = $openstack->networkingV2(["region"=>"RegionOne"]);
|
||||
$ls = $networking->listSubnets();
|
||||
|
||||
foreach ($ls as $subnet) {
|
||||
echo $subnet->cidr."<br>";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
0
server/Test/DisplayNetIds.php
Normal file → Executable file
0
server/Test/DisplayNetIds.php
Normal file → Executable file
146
server/Test/NetworkLayer3Tests.php
Normal file
146
server/Test/NetworkLayer3Tests.php
Normal file
|
@ -0,0 +1,146 @@
|
|||
<?php
|
||||
|
||||
include('InitTest.php');
|
||||
include_once("../core/Compute.php");
|
||||
include_once("../core/Network.php");
|
||||
include_once("../core/NetworkLayer3.php");
|
||||
|
||||
$compute = new Compute($App);
|
||||
$network = new Network($App);
|
||||
$networkLayer3 = new NetworkLayer3($App);
|
||||
|
||||
|
||||
// Liste des serveurs
|
||||
echo "Liste des serveurs : </br>";
|
||||
$compute->action("listServers");
|
||||
$servers = json_decode($App->show(), true)["Servers"];
|
||||
$id = null;
|
||||
foreach($servers as $server){
|
||||
echo $server['name']." ".$server['id']." ".$server['ipv4']."<br>";
|
||||
if(strcmp($server['name'], "bob")){
|
||||
$id = $server['id'];
|
||||
}
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
|
||||
// Liste des networks
|
||||
echo "Liste des network : </br>";
|
||||
$network->action("list_network_ids");
|
||||
$servers = json_decode($App->show(), true)["ListNetworkIds"];
|
||||
$id = null;
|
||||
foreach($servers as $server){
|
||||
echo $server."<br>";
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
|
||||
// Liste des floatingip
|
||||
echo "Liste des floatingip : </br>";
|
||||
$networkLayer3->action("listFloatingIp");
|
||||
$listFloatingIp = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
$id = null;
|
||||
foreach ($listFloatingIp as $floatIp){
|
||||
echo $floatIp['floatingIpAddress']." ".$floatIp['id']." ".$floatIp["status"]."<br>";
|
||||
$id = $floatIp['id'];
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
|
||||
// get floatingip
|
||||
echo "Get floatingip : </br>";
|
||||
$App->setPostParam('id', $id);
|
||||
$networkLayer3->action("getFloatingIp");
|
||||
$getFloatingIp = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
echo $getFloatingIp['id']."<br>";
|
||||
echo "</br>";
|
||||
|
||||
|
||||
/*
|
||||
// Création d'une ip flotante
|
||||
$opt = array();
|
||||
$opt['floatingNetworkId'] = "251b4641-20ff-4a72-8549-1758788b51ce";
|
||||
|
||||
$App->setPostParam('opt', $opt);
|
||||
$networkLayer3->action("createFloatingIp");
|
||||
$float = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
if(!isset($float)){
|
||||
echo "Erreur pendant la création</br>";
|
||||
}
|
||||
echo "</br>";
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
// Suppression d'une ip flotante
|
||||
$App->setPostParam('id', $id);
|
||||
$networkLayer3->action("deleteFloatingIp");
|
||||
*/
|
||||
|
||||
|
||||
// Liste des floatingip
|
||||
echo "Liste des floatingip : </br>";
|
||||
$networkLayer3->action("listFloatingIp");
|
||||
$listFloatingIp = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
foreach ($listFloatingIp as $floatIp){
|
||||
echo $floatIp['floatingIpAddress']." ".$floatIp['id']." ".$floatIp["status"]."<br>";
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
|
||||
// Liste des routeurs
|
||||
echo "Liste des routeurs : </br>";
|
||||
$networkLayer3->action("listRouters");
|
||||
$listRouters = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
foreach ($listRouters as $router){
|
||||
echo $router['name']." ".$router['id']."<br>";
|
||||
if(strcmp($router['name'], "Test")){
|
||||
$id = $router['id'];
|
||||
}
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
|
||||
// get floatingip
|
||||
echo "Get router : </br>";
|
||||
$App->setPostParam('id', $id);
|
||||
$networkLayer3->action("getRouter");
|
||||
$getRouter = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
echo $getRouter['id']."<br>";
|
||||
echo "</br>";
|
||||
|
||||
|
||||
/*
|
||||
// Création d'un routeur'
|
||||
$opt = array();
|
||||
$optGate = array();
|
||||
$optGate['networkId'] = "251b4641-20ff-4a72-8549-1758788b51ce";
|
||||
$opt['externalGatewayInfo'] = $optGate;
|
||||
$opt['name'] = "Test";
|
||||
$App->setPostParam('opt', $opt);
|
||||
$networkLayer3->action("createRouter");
|
||||
$r = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
if(!isset($r)){
|
||||
echo "Erreur pendant la création</br>";
|
||||
}
|
||||
echo "</br>";
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
// Suppression d'un routeur
|
||||
$App->setPostParam('id', $id);
|
||||
$networkLayer3->action("deleteRouter");
|
||||
echo "</br>";
|
||||
*/
|
||||
|
||||
|
||||
// Liste des routeurs
|
||||
echo "Liste des routeurs : </br>";
|
||||
$networkLayer3->action("listRouters");
|
||||
$listRouters = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
foreach ($listRouters as $router){
|
||||
echo $router['name']." ".$router['id']."<br>";
|
||||
}
|
||||
|
||||
?>
|
20
server/Test/automatingTests.php
Executable file
20
server/Test/automatingTests.php
Executable file
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
include('InitTest.php');
|
||||
include_once("../core/Automating.php");
|
||||
|
||||
$automating = new Automating($App);
|
||||
|
||||
//$id = // id du réseau
|
||||
|
||||
/*
|
||||
// Création serveur avec ip publique
|
||||
echo "Test création serveur avec ip publique : </br>";
|
||||
$App->setPostParam('networkId', $id);
|
||||
$App->setPostParam('imageName', "ImageTest");
|
||||
$App->setPostParam('serverName', "ServerTest");
|
||||
$App->setPostParam('flavor', 1);
|
||||
$compute->action("createPublicServer");
|
||||
$servers = json_decode($App->show(), true)["Automating"];
|
||||
*/
|
||||
|
||||
?>
|
0
server/Test/computeTest.php
Normal file → Executable file
0
server/Test/computeTest.php
Normal file → Executable file
0
server/Test/create_network.php
Normal file → Executable file
0
server/Test/create_network.php
Normal file → Executable file
0
server/Test/create_subnet.php
Normal file → Executable file
0
server/Test/create_subnet.php
Normal file → Executable file
0
server/Test/genTokenOptionsTest.php
Normal file → Executable file
0
server/Test/genTokenOptionsTest.php
Normal file → Executable file
34
server/Test/getIdNetwork.php
Executable file
34
server/Test/getIdNetwork.php
Executable file
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
ini_set('display_errors', 1);
|
||||
date_default_timezone_set("Europe/Paris");
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
$options = Array();
|
||||
$options["user"] = Array("name"=>"admin", "password"=>"ae5or6cn", "domain"=>["id"=>"Default"]);
|
||||
$options["scope"] = Array("project"=>Array("name"=>"admin", "domain"=>["id"=>"Default"]));
|
||||
$options["authUrl"] = "http://148.60.11.31:5000/v3";
|
||||
$openstack = new OpenStack\OpenStack($options);
|
||||
$networking = $openstack->networkingV2(["region"=>"RegionOne"]);
|
||||
|
||||
$ls = $networking->getNetwork('5f78d3c1-1f53-4be7-897b-cf3c797961e0');
|
||||
try{
|
||||
$ls->retrieve();
|
||||
|
||||
|
||||
|
||||
echo "oui";}
|
||||
|
||||
catch (OpenStack\Common\Error\BadResponseError $e){
|
||||
echo "non"; }
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
26
server/Test/getNetwork.php
Executable file
26
server/Test/getNetwork.php
Executable file
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
ini_set('display_errors', 1);
|
||||
date_default_timezone_set("Europe/Paris");
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
$options = Array();
|
||||
$options["user"] = Array("name"=>"admin", "password"=>"ae5or6cn", "domain"=>["id"=>"Default"]);
|
||||
$options["scope"] = Array("project"=>Array("name"=>"admin", "domain"=>["id"=>"Default"]));
|
||||
$options["authUrl"] = "http://148.60.11.31:5000/v3";
|
||||
$openstack = new OpenStack\OpenStack($options);
|
||||
$networking = $openstack->networkingV2(["region"=>"RegionOne"]);
|
||||
$ls = $networking->listNetworks();
|
||||
|
||||
foreach ($ls as $subnet) {
|
||||
echo $subnet->id."<br>";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
157
server/Test/imageTests.php
Normal file → Executable file
157
server/Test/imageTests.php
Normal file → Executable file
|
@ -1,68 +1,125 @@
|
|||
<?php
|
||||
include('InitTest.php');
|
||||
include_once("../core/Image.php");
|
||||
include_once("../core/Compute.php");
|
||||
|
||||
$image = new Image($App);
|
||||
$compute = new Compute($App);
|
||||
|
||||
// Création image
|
||||
/*
|
||||
echo "Création image :</br>";
|
||||
$opt = Array();
|
||||
$opt['name'] = "Test";
|
||||
$opt['tags'] = ['test', 'openstack'];
|
||||
//$opt['containerFormat'] = 'ami';
|
||||
//$opt['diskFormat'] = 'iso';
|
||||
$opt['visibility'] = 'public';
|
||||
//$opt['visibility'] = 'public';
|
||||
$opt['minDisk'] = 1;
|
||||
$opt['protected'] = false;
|
||||
$opt['minRam'] = 10;
|
||||
|
||||
//$new_image = $image->createImage($opt);
|
||||
|
||||
//Liste des images
|
||||
$image->action("listImage");
|
||||
//$images = $image->listImage();
|
||||
$im = $App->show();
|
||||
$images = json_decode($im, true)["Images"];
|
||||
if(isset($images)){
|
||||
echo "Images présentes :";
|
||||
echo "</br>";
|
||||
foreach($images as $i){
|
||||
echo $i['name'];
|
||||
echo "</br>";
|
||||
}
|
||||
echo "</br>";
|
||||
|
||||
if(isset($list)){
|
||||
foreach ($list as $l) {
|
||||
echo $l;
|
||||
echo "</br>";
|
||||
}
|
||||
}
|
||||
}
|
||||
else{
|
||||
echo "Aucune image présente\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Détails Image
|
||||
//$details = $image->imageDetails($id_image);
|
||||
|
||||
//$image->deleteImage('123456');
|
||||
|
||||
//$image->desactivateImage($id_image);
|
||||
//$image->reactivateImage($id_image);
|
||||
|
||||
//$file_name = "/home/yogg/Downloads/TinyCore-6.4.1.iso";
|
||||
//$image->uploadImage($id_image, $file_name);
|
||||
|
||||
//$image->downloadImage($id_image);
|
||||
|
||||
/*
|
||||
$opt_update = Array();
|
||||
$opt_update['name'] = "Test";
|
||||
$opt_update['tags'] = null;
|
||||
|
||||
$update = $image->updateImage($id_image, $opt_update);
|
||||
echo $update->name;
|
||||
$App->setPostParam('opt', $opt);
|
||||
$image->action("createImage");
|
||||
$retCreate = json_decode($App->show(), true)["Images"];
|
||||
$idNew = $retCreate['id'];
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
// Liste images
|
||||
$image->action("listImage");
|
||||
$im = $App->show();
|
||||
$images = json_decode($im, true)["Images"];
|
||||
|
||||
$res;
|
||||
echo "List images :</br></br>";
|
||||
foreach($images as $i){
|
||||
$name = $i['name'];
|
||||
if(strcmp($name,"Test") == 0)
|
||||
{
|
||||
$res = $i['id'];
|
||||
}
|
||||
echo $name."</br>"; // Nom
|
||||
echo $i['status']."</br>"; // Status
|
||||
$id = $i['id']; // Id
|
||||
echo $id."</br>";
|
||||
/*foreach ($i['tags'] as $tag) { // Tags
|
||||
echo $tag."</br>";
|
||||
}*/
|
||||
echo "</br>";
|
||||
}
|
||||
|
||||
// Delete Image
|
||||
/*
|
||||
$App->setPostParam('id', $res);
|
||||
$image->action("deleteImage");
|
||||
*/
|
||||
|
||||
/*
|
||||
// Details images
|
||||
echo "Détail image :</br>";
|
||||
$App->setPostParam('id', $id);
|
||||
$image->action("detailsImage");
|
||||
$retDetails = json_decode($App->show(), true)["Images"];
|
||||
echo $retDetails['id']."</br>";
|
||||
echo "</br>";
|
||||
*/
|
||||
|
||||
/*
|
||||
// Download image
|
||||
$App->setPostParam('id', $id);
|
||||
$image->action("downloadImage");
|
||||
*/
|
||||
|
||||
|
||||
// Desactivate Images
|
||||
/*
|
||||
echo "Desactivate image : </br>";
|
||||
echo $id."</br>";
|
||||
$App->setPostParam('id', $id);
|
||||
$err = $image->action("desactivateImage");
|
||||
echo "</br>";
|
||||
*/
|
||||
|
||||
|
||||
// Reactivate Images
|
||||
/*
|
||||
echo $id."</br>";
|
||||
$App->setPostParam('id', $res);
|
||||
$image->action("reactivateImage");
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
// Details images
|
||||
echo "Update image :</br>";
|
||||
$optUpdate = Array();
|
||||
$optUpdate['tags'] = ['ciros', 'testUpdate'];
|
||||
$App->setPostParam('id', $id);
|
||||
$App->setPostParam('opt', $optUpdate);
|
||||
$image->action("updateImage");
|
||||
$retDetails = json_decode($App->show(), true)["Images"];
|
||||
foreach ($retDetails['tags'] as $tag) { // Tags
|
||||
echo $tag."</br>";
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
echo "Flavors: ";
|
||||
echo "</br>";
|
||||
$compute->action("listFlavors");
|
||||
$flavors = json_decode($App->show(), true)["Flavors"];
|
||||
|
||||
foreach($flavors as $f){
|
||||
echo "Id=".$f['id'].", ";
|
||||
echo "name=".$f['name'].", ";
|
||||
echo "ram=".$f['ram'].", ";
|
||||
echo "disk=".$f['disk'].", ";
|
||||
echo "vcpus=".$f['vcpus'];
|
||||
echo "</br>";
|
||||
}
|
||||
*/
|
||||
?>
|
3
server/composer.json
Normal file → Executable file
3
server/composer.json
Normal file → Executable file
|
@ -1,6 +1,5 @@
|
|||
{
|
||||
"require": {
|
||||
"php-opencloud/openstack": "dev-master",
|
||||
"php-opencloud/common": "dev-master"
|
||||
"php-opencloud/openstack": "dev-master"
|
||||
}
|
||||
}
|
||||
|
|
403
server/composer.lock
generated
403
server/composer.lock
generated
|
@ -1,403 +0,0 @@
|
|||
{
|
||||
"_readme": [
|
||||
"This file locks the dependencies of your project to a known state",
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"hash": "7647ed348aee68f2db6b71e4d2fb1fe7",
|
||||
"content-hash": "82731500d050a65f09e92b70c1f96ea9",
|
||||
"packages": [
|
||||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"version": "6.1.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/guzzle.git",
|
||||
"reference": "c6851d6e48f63b69357cbfa55bca116448140e0c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/c6851d6e48f63b69357cbfa55bca116448140e0c",
|
||||
"reference": "c6851d6e48f63b69357cbfa55bca116448140e0c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"guzzlehttp/promises": "~1.0",
|
||||
"guzzlehttp/psr7": "~1.1",
|
||||
"php": ">=5.5.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-curl": "*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "6.1-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "Guzzle is a PHP HTTP client library",
|
||||
"homepage": "http://guzzlephp.org/",
|
||||
"keywords": [
|
||||
"client",
|
||||
"curl",
|
||||
"framework",
|
||||
"http",
|
||||
"http client",
|
||||
"rest",
|
||||
"web service"
|
||||
],
|
||||
"time": "2015-11-23 00:47:50"
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/promises",
|
||||
"version": "1.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/promises.git",
|
||||
"reference": "bb9024c526b22f3fe6ae55a561fd70653d470aa8"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/promises/zipball/bb9024c526b22f3fe6ae55a561fd70653d470aa8",
|
||||
"reference": "bb9024c526b22f3fe6ae55a561fd70653d470aa8",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.5.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~4.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "Guzzle promises library",
|
||||
"keywords": [
|
||||
"promise"
|
||||
],
|
||||
"time": "2016-03-08 01:15:46"
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/psr7",
|
||||
"version": "1.2.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/psr7.git",
|
||||
"reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/psr7/zipball/2e89629ff057ebb49492ba08e6995d3a6a80021b",
|
||||
"reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.4.0",
|
||||
"psr/http-message": "~1.0"
|
||||
},
|
||||
"provide": {
|
||||
"psr/http-message-implementation": "1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~4.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Psr7\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "PSR-7 message implementation",
|
||||
"keywords": [
|
||||
"http",
|
||||
"message",
|
||||
"stream",
|
||||
"uri"
|
||||
],
|
||||
"time": "2016-02-18 21:54:00"
|
||||
},
|
||||
{
|
||||
"name": "justinrainbow/json-schema",
|
||||
"version": "1.6.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/justinrainbow/json-schema.git",
|
||||
"reference": "cc84765fb7317f6b07bd8ac78364747f95b86341"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/cc84765fb7317f6b07bd8ac78364747f95b86341",
|
||||
"reference": "cc84765fb7317f6b07bd8ac78364747f95b86341",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3.29"
|
||||
},
|
||||
"require-dev": {
|
||||
"json-schema/json-schema-test-suite": "1.1.0",
|
||||
"phpdocumentor/phpdocumentor": "~2",
|
||||
"phpunit/phpunit": "~3.7"
|
||||
},
|
||||
"bin": [
|
||||
"bin/validate-json"
|
||||
],
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.6.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"JsonSchema\\": "src/JsonSchema/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"BSD-3-Clause"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Bruno Prieto Reis",
|
||||
"email": "bruno.p.reis@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Justin Rainbow",
|
||||
"email": "justin.rainbow@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Igor Wiedler",
|
||||
"email": "igor@wiedler.ch"
|
||||
},
|
||||
{
|
||||
"name": "Robert Schönthal",
|
||||
"email": "seroscho@googlemail.com"
|
||||
}
|
||||
],
|
||||
"description": "A library to validate a json schema.",
|
||||
"homepage": "https://github.com/justinrainbow/json-schema",
|
||||
"keywords": [
|
||||
"json",
|
||||
"schema"
|
||||
],
|
||||
"time": "2016-01-25 15:43:01"
|
||||
},
|
||||
{
|
||||
"name": "php-opencloud/common",
|
||||
"version": "dev-master",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-opencloud/common.git",
|
||||
"reference": "fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-opencloud/common/zipball/fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62",
|
||||
"reference": "fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"guzzlehttp/guzzle": "~6.1",
|
||||
"justinrainbow/json-schema": "~1.3",
|
||||
"php": "~7.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"fabpot/php-cs-fixer": "~1.0",
|
||||
"jakub-onderka/php-parallel-lint": "0.*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0",
|
||||
"sami/sami": "dev-master",
|
||||
"satooshi/php-coveralls": "~1.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"OpenCloud\\": "src/",
|
||||
"OpenCloud\\Test\\": "tests/unit/",
|
||||
"OpenCloud\\Integration\\": "tests/integration/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Jamie Hannaford",
|
||||
"email": "jamie.hannaford@rackspace.com",
|
||||
"homepage": "https://github.com/jamiehannaford"
|
||||
}
|
||||
],
|
||||
"time": "2016-03-08 12:56:34"
|
||||
},
|
||||
{
|
||||
"name": "php-opencloud/openstack",
|
||||
"version": "dev-master",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-opencloud/openstack.git",
|
||||
"reference": "f2ee77024843659d970817a9e7055bb40a3724f9"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
<<<<<<< HEAD
|
||||
<<<<<<< Updated upstream
|
||||
"url": "https://api.github.com/repos/php-opencloud/openstack/zipball/15aca73f423166c7ef8337ba08615c103c66e931",
|
||||
=======
|
||||
"url": "https://api.github.com/repos/php-opencloud/openstack/zipball/f2ee77024843659d970817a9e7055bb40a3724f9",
|
||||
>>>>>>> develop
|
||||
"reference": "15aca73f423166c7ef8337ba08615c103c66e931",
|
||||
=======
|
||||
"url": "https://api.github.com/repos/php-opencloud/openstack/zipball/f2ee77024843659d970817a9e7055bb40a3724f9",
|
||||
"reference": "f2ee77024843659d970817a9e7055bb40a3724f9",
|
||||
>>>>>>> Stashed changes
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php-opencloud/common": "dev-master"
|
||||
},
|
||||
"require-dev": {
|
||||
"fabpot/php-cs-fixer": "~1.0",
|
||||
"jakub-onderka/php-parallel-lint": "0.*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0",
|
||||
"sami/sami": "dev-master",
|
||||
"satooshi/php-coveralls": "~1.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"OpenStack\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Jamie Hannaford",
|
||||
"email": "jamie.hannaford@rackspace.com",
|
||||
"homepage": "https://github.com/jamiehannaford"
|
||||
}
|
||||
],
|
||||
"time": "2016-03-08 14:37:14"
|
||||
},
|
||||
{
|
||||
"name": "psr/http-message",
|
||||
"version": "1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-fig/http-message.git",
|
||||
"reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-fig/http-message/zipball/85d63699f0dbedb190bbd4b0d2b9dc707ea4c298",
|
||||
"reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Psr\\Http\\Message\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "PHP-FIG",
|
||||
"homepage": "http://www.php-fig.org/"
|
||||
}
|
||||
],
|
||||
"description": "Common interface for HTTP messages",
|
||||
"keywords": [
|
||||
"http",
|
||||
"http-message",
|
||||
"psr",
|
||||
"psr-7",
|
||||
"request",
|
||||
"response"
|
||||
],
|
||||
"time": "2015-05-04 20:22:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
"aliases": [],
|
||||
"minimum-stability": "stable",
|
||||
"stability-flags": {
|
||||
"php-opencloud/openstack": 20,
|
||||
"php-opencloud/common": 20
|
||||
},
|
||||
"prefer-stable": false,
|
||||
"prefer-lowest": false,
|
||||
"platform": [],
|
||||
"platform-dev": []
|
||||
}
|
0
server/composer.phar
Normal file → Executable file
0
server/composer.phar
Normal file → Executable file
21
server/config.inc.php
Normal file → Executable file
21
server/config.inc.php
Normal file → Executable file
|
@ -1,10 +1,21 @@
|
|||
<?php
|
||||
date_default_timezone_set('Europe/Paris');
|
||||
/**
|
||||
* File containing global config options for the API.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*
|
||||
*/
|
||||
|
||||
$config = Array();
|
||||
|
||||
$config["modules_enabled"] = "";
|
||||
$config["urlAuth"] = "http://148.60.11.31:5000/v3";
|
||||
date_default_timezone_set('Europe/Paris');
|
||||
|
||||
$config = Array();
|
||||
|
||||
$config["modules_enabled"] = "";
|
||||
$config["urlAuth"] = "http://148.60.11.31:5000/v3";
|
||||
$config["tokenTime"] = 60; //minutes
|
||||
?>
|
||||
|
||||
|
||||
|
|
|
@ -1,35 +1,73 @@
|
|||
<?php
|
||||
include_once("core/Plugin_Api.php");
|
||||
/**
|
||||
* File containing the identity Class.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* Library token management override
|
||||
*/
|
||||
include_once("core/LibOverride/genTokenOptions.php");
|
||||
include_once("core/ErrorManagement.php");
|
||||
|
||||
//Library loading
|
||||
use OpenCloud\Common\Error\BadResponseError;
|
||||
use OpenCloud\Common\Error\BaseError;
|
||||
use OpenCloud\Common\Error\NotImplementedError;
|
||||
use OpenCloud\Common\Error\UserInputError;
|
||||
|
||||
/**
|
||||
* App Class of the back-end application
|
||||
*
|
||||
* This class allow the communication between the front-end application and
|
||||
* the library which allow to send requests to an Openstack instance.
|
||||
*
|
||||
*/
|
||||
class App{
|
||||
|
||||
/** @var OpenStack\OpenStack $openstack protected, contains the main library object */
|
||||
protected $openstack;
|
||||
protected $pluginsApi;
|
||||
/** @var Array $postParams protected, contains the post parameters */
|
||||
protected $postParams;
|
||||
/** @var genTokenOptions $tokenClass protected, contains the class object for the authentication override of the library */
|
||||
protected $tokenClass;
|
||||
/** @var String $tokenPost protected, contains the token given in parameter */
|
||||
protected $tokenPost;
|
||||
/** @var errorManagement $errorClass protected, contains the errorManagement object */
|
||||
protected $errorClass;
|
||||
/** @var Array $output protected, contains the result for the API call */
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* App constructor
|
||||
*
|
||||
* @param Array $args Args for the OpenStack Library
|
||||
*
|
||||
* @return App object
|
||||
*/
|
||||
public function __construct($args){
|
||||
|
||||
$this->tokenPost = NULL;
|
||||
$this->tokenClass = new genTokenOptions($args);
|
||||
$this->openstack = new OpenStack\OpenStack([]);
|
||||
$this->pluginsApi = plugin_api::getInstance();
|
||||
$this->openstack = new OpenStack\OpenStack(['authUrl' => $args["authUrl"]]);
|
||||
$this->errorClass = new errorManagement($this);
|
||||
$this->output = array();
|
||||
$this->postParams = $_POST;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the class var $tokenPost and load the token
|
||||
* into the genTokenOptions Class
|
||||
*
|
||||
* @param String $token token to be set
|
||||
*
|
||||
*/
|
||||
public function setToken($token){
|
||||
|
||||
$this->tokenPost = $token;
|
||||
|
@ -37,33 +75,59 @@ class App{
|
|||
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the expiration of the token
|
||||
*
|
||||
* @return Boolean if the token is not expired
|
||||
*/
|
||||
public function checkToken(){
|
||||
return $this->tokenClass->checkToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the service Class given the name in parameter
|
||||
*
|
||||
* @param String $service Name of the service
|
||||
*
|
||||
* @return Core object
|
||||
*/
|
||||
public function getLibClass($service){
|
||||
|
||||
switch($service){
|
||||
case "Identity":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genIdentityToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->identityV3($opt);
|
||||
break;
|
||||
case "Image":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genImageToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->imagesV2($opt);
|
||||
break;
|
||||
case "Network":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genNetworkToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->networkingV2($opt);
|
||||
break;
|
||||
case "Compute":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genComputeToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->computeV2($opt);
|
||||
break;
|
||||
case "Identity":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genIdentityToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->identityV3($opt);
|
||||
break;
|
||||
case "Image":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genImageToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->imagesV2($opt);
|
||||
break;
|
||||
case "Network":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genNetworkToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->networkingV2($opt);
|
||||
break;
|
||||
case "Compute":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genComputeToken();
|
||||
$opt = $this->tokenClass->getOptions($service);
|
||||
return $this->openstack->computeV2($opt);
|
||||
break;
|
||||
case "NetworkLayer3":
|
||||
if($this->tokenPost == NULL) $this->tokenClass->genNetworkToken();
|
||||
$opt = $this->tokenClass->getOptions('Network');
|
||||
return $this->openstack->networkingV2ExtLayer3($opt);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the token for the different services in OpenStack
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function authenticate(){
|
||||
|
||||
try{
|
||||
|
@ -75,16 +139,21 @@ class App{
|
|||
$this->setOutput("token", $this->tokenClass->getBackup());
|
||||
}catch(BadResponseError $e){
|
||||
$this->errorClass->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
}catch(UserInputError $e){
|
||||
$this->errorClass->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
}catch(BaseError $e){
|
||||
$this->errorClass->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
}catch(NotImplementedError $e){
|
||||
$this->errorClass->NotImplementedHandler($e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the openstack services' token
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function deauthenticate(){
|
||||
|
||||
try{
|
||||
|
@ -97,37 +166,79 @@ class App{
|
|||
$this->setOutput("deauthenticate", "Ok");
|
||||
}catch(BadResponseError $e){
|
||||
$this->errorClass->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
}catch(UserInputError $e){
|
||||
$this->errorClass->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
}catch(BaseError $e){
|
||||
$this->errorClass->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
}catch(NotImplementedError $e){
|
||||
$this->errorClass->NotImplementedHandler($e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a post parameter given its name
|
||||
*
|
||||
* @param String $name Expected post parameter's name
|
||||
*
|
||||
* @return Object Post value
|
||||
*/
|
||||
public function getPostParam($name){
|
||||
|
||||
if(isset($this->postParams[$name])){
|
||||
return $this->postParams[$name];
|
||||
}else{
|
||||
$this->setOutput("Error", "Missing parameter ".$name);
|
||||
}
|
||||
|
||||
return $this->postParams[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a post parameter for automating task
|
||||
*
|
||||
* @param String $param Name for the Post entry
|
||||
* @param Object $value Value for the Post entry
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setPostParam($param, $value){
|
||||
|
||||
$this->postParams[$param] = $value;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new output message
|
||||
*
|
||||
* @param String $key Array key for the message
|
||||
* @param Array $out Message's value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setOutput($key, $out){
|
||||
|
||||
$this->output[$key] = $out;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the errorManagement instance Object
|
||||
*
|
||||
* @return errorManagement object
|
||||
*/
|
||||
public function getErrorInstance(){
|
||||
|
||||
return $this->errorClass;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Output the messages to be send to the client
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function show(){
|
||||
echo json_encode($this->output);
|
||||
//error_log(var_dump(json_encode($this->output), true), 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
133
server/core/Automating.php
Executable file
133
server/core/Automating.php
Executable file
|
@ -0,0 +1,133 @@
|
|||
<?php
|
||||
/**
|
||||
* File containing the Automating Class.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Evan Pisani 'yogg at epsina . com', bhupi
|
||||
*
|
||||
*/
|
||||
|
||||
include("Image.php");
|
||||
include("Network.php");
|
||||
include("Compute.php");
|
||||
include("NetworkLayer3.php");
|
||||
include("CoreInterface.php");
|
||||
|
||||
/**
|
||||
* automating Class of the back-end application
|
||||
*
|
||||
* Contains the different function to automate some action
|
||||
*
|
||||
*/
|
||||
class automating implements Core{
|
||||
|
||||
/** @var App $compute protected, contains a Core compute object */
|
||||
protected $compute;
|
||||
/** @var App $image protected, contains a Core image object */
|
||||
protected $image;
|
||||
/** @var App $network protected, contains a Core network object */
|
||||
protected $network;
|
||||
/** @var App $networkLayer3 protected, contains a Core networkLayer3 object */
|
||||
protected $networkLayer3;
|
||||
/** @var App $app protected, contains the main app object */
|
||||
protected $app;
|
||||
|
||||
/**
|
||||
* automating class constructor
|
||||
*
|
||||
* @param App $app the main app object
|
||||
*
|
||||
* @return automating Object
|
||||
*/
|
||||
public function __construct($app){
|
||||
$this->app = $app;
|
||||
$compute = new Compute($app);
|
||||
$image = new Image($app);
|
||||
$network = new Network($app);
|
||||
$networkLayer3 = new NetworkLayer3($app);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an action
|
||||
*
|
||||
* @param String $action name of another function of this class
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function action($action){
|
||||
$this->{$action.""}();
|
||||
}
|
||||
|
||||
/**
|
||||
* create a new server and associate a public ip
|
||||
*
|
||||
* @param String $networkId the id of the network where the server will be created
|
||||
* @param String $imageName name of the new image
|
||||
* @param String $serverName name ofthe new server
|
||||
* @param String $flavor kind of server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function createPublicServer()
|
||||
{
|
||||
$networkId = $this->app->getPostParam('networkId');
|
||||
$imageName = $this->app->getPostParam('imageName');
|
||||
$serverName = $this->app->getPostParam('serverName');
|
||||
$flavor = $this->app->getPostParam('flavor');
|
||||
|
||||
if(!isset($imageName)){
|
||||
$this->app->setOutput("Error", "Incorrect imageName parameter");
|
||||
}
|
||||
else if(!isset($serverName)){
|
||||
$this->app->setOutput("Error", "Incorrect serverName parameter");
|
||||
}
|
||||
else if(!isset($flavor)){
|
||||
$this->app->setOutput("Error", "Incorrect flavor parameter");
|
||||
}
|
||||
else{
|
||||
// Création image
|
||||
$opt = array();
|
||||
$opt['name'] = $imageName;
|
||||
$image->setPostParam('opt', $opt);
|
||||
$image->action("createImage");
|
||||
$image = json_decode($this->app->show(), true)["Images"];
|
||||
|
||||
// Création server
|
||||
$compute->setPostParam('name', $serverName);
|
||||
$compute->setPostParam('imageId', $image['id']);
|
||||
$compute->setPostParam('flavorId', $flavor);
|
||||
$compute->action("createServer");
|
||||
$server = json_decode($this->app->show(), true)["Compute"];
|
||||
|
||||
// liste des adresses ip publiques diponibles
|
||||
$networkLayer3->action("listFloatingIp");
|
||||
$listFloatingIp = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
$ip = null;
|
||||
foreach ($listFloatingIp as $f) {
|
||||
if(strcmp($f['status'], "DOWN")){
|
||||
$ip = $f;
|
||||
}
|
||||
}
|
||||
|
||||
// Si pas d'ip publique disponible on en créé une
|
||||
if(!isset($ip)){
|
||||
// Ajout adresse IP public
|
||||
$optIp = array();
|
||||
$opt['floatingNetworkId'] = $networkId;
|
||||
$floatingIp->setPostParam('opt', $optIp);
|
||||
$networkLayer3->action("createFloatingIp");
|
||||
$ip = json_decode($App->show(), true)["NetworkLayer3"];
|
||||
}
|
||||
|
||||
// Association de l'ip publique au serveur
|
||||
/*
|
||||
* API non diponible pour le moment
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
|
@ -1,21 +1,45 @@
|
|||
<?php
|
||||
//namespace istic-openstack\Server\core;
|
||||
/**
|
||||
* File containing the compute Class.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author bhupi
|
||||
*
|
||||
*/
|
||||
|
||||
use OpenCloud\Common\Error;
|
||||
|
||||
class compute
|
||||
include("CoreInterface.php");
|
||||
/**
|
||||
* Compute Class of the back-end application
|
||||
*
|
||||
* Management of Servers
|
||||
*
|
||||
*/
|
||||
class compute implements Core
|
||||
{
|
||||
/** @var App $app protected, contains the main app object */
|
||||
protected $app;
|
||||
/** @var App $app protected, contains the main app object */
|
||||
protected $app;
|
||||
|
||||
/** @var OpenStack\Identity $libClass protected, contains the library Compute object */
|
||||
protected $libClass;
|
||||
/** @var OpenStack\Compute $libClass protected, contains the library Compute object */
|
||||
protected $libClass;
|
||||
|
||||
|
||||
public function __construct($app)
|
||||
{
|
||||
$this->app = $app;
|
||||
$this->libClass = $app->getLibClass("Compute");
|
||||
}
|
||||
/**
|
||||
* Compute constructor
|
||||
*
|
||||
* @param App $args the main app object
|
||||
*
|
||||
* @return compute Object
|
||||
*/
|
||||
public function __construct($app)
|
||||
{
|
||||
$this->app = $app;
|
||||
$this->libClass = $app->getLibClass("Compute");
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an action
|
||||
*
|
||||
|
@ -25,342 +49,625 @@ class compute
|
|||
*/
|
||||
public function action($action){
|
||||
|
||||
$this->{$action.""}();
|
||||
$this->{$action.""}();
|
||||
|
||||
}
|
||||
/**
|
||||
* List servers.
|
||||
* @return array
|
||||
*/
|
||||
public function listServers()
|
||||
{
|
||||
$serverList = $this->libClass->listServers(true);
|
||||
$servers = Array();
|
||||
foreach($serverList as $server){
|
||||
$servers[$server->id] = Array();
|
||||
$server->flavor->retrieve();
|
||||
$server->image->retrieve();
|
||||
$server->retrieve();
|
||||
$servers[$server->id]["id"] = $server->id;
|
||||
$servers[$server->id]["name"] = $server->name;
|
||||
$servers[$server->id]["image"] = $server->image;
|
||||
$servers[$server->id]["ram"] = $server->flavor->ram;
|
||||
$servers[$server->id]["disk"] = $server->flavor->disk;
|
||||
$servers[$server->id]["flavor"] = $server->flavor;
|
||||
$servers[$server->id]["status"] = $server->status;
|
||||
$servers[$server->id]["created"] = $server->created;
|
||||
$servers[$server->id]["updated"] = $server->updated;
|
||||
$servers[$server->id]["ipv4"] = $server->ipv4;
|
||||
$servers[$server->id]["ipv6"] = $server->ipv6;
|
||||
$servers[$server->id]["progress"] = $server->progress;
|
||||
$servers[$server->id]["hostId"] = $server->hostId;
|
||||
$servers[$server->id]["tenantId"] = $server->tenantId;
|
||||
$servers[$server->id]["userId"] = $server->userId;
|
||||
$servers[$server->id]["taskState"] = $server->taskState;
|
||||
$servers[$server->id]["addresses"] = $server->addresses;
|
||||
$servers[$server->id]["links"] = $server->links;
|
||||
$servers[$server->id]["metadata"] = $server->metadata;
|
||||
|
||||
/**
|
||||
* List servers.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function listServers()
|
||||
{
|
||||
try{
|
||||
$serverList = $this->libClass->listServers(true);
|
||||
$servers = Array();
|
||||
foreach($serverList as $server){
|
||||
$servers[$server->id] = Array();
|
||||
$server->flavor->retrieve();
|
||||
$server->image->retrieve();
|
||||
$server->retrieve();
|
||||
$servers[$server->id]["id"] = $server->id;
|
||||
$servers[$server->id]["name"] = $server->name;
|
||||
$servers[$server->id]["image"] = $server->image;
|
||||
$servers[$server->id]["ram"] = $server->flavor->ram;
|
||||
$servers[$server->id]["disk"] = $server->flavor->disk;
|
||||
$servers[$server->id]["flavor"] = $server->flavor;
|
||||
$servers[$server->id]["status"] = $server->status;
|
||||
$servers[$server->id]["created"] = $server->created;
|
||||
$servers[$server->id]["updated"] = $server->updated;
|
||||
$servers[$server->id]["ipv4"] = $server->ipv4;
|
||||
$servers[$server->id]["ipv6"] = $server->ipv6;
|
||||
$servers[$server->id]["progress"] = $server->progress;
|
||||
$servers[$server->id]["hostId"] = $server->hostId;
|
||||
$servers[$server->id]["tenantId"] = $server->tenantId;
|
||||
$servers[$server->id]["userId"] = $server->userId;
|
||||
$servers[$server->id]["taskState"] = $server->taskState;
|
||||
$servers[$server->id]["addresses"] = $server->addresses;
|
||||
$servers[$server->id]["links"] = $server->links;
|
||||
$servers[$server->id]["metadata"] = $server->metadata;
|
||||
}
|
||||
$this->app->setOutput("Servers", $servers);
|
||||
}
|
||||
$this->app->setOutput("Servers", $servers);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* List flavors.
|
||||
* @return array
|
||||
*/
|
||||
public function listFlavors()
|
||||
{
|
||||
$flavorList = $this->libClass->listFlavors();
|
||||
$flavors = Array();
|
||||
foreach($flavorList as $flavor){
|
||||
$flavors[$flavor->id] = Array();
|
||||
$flavor->retrieve();
|
||||
$flavors[$flavor->id]["id"] = $flavor->id;
|
||||
$flavors[$flavor->id]["name"] = $flavor->name;
|
||||
$flavors[$flavor->id]["ram"] = $flavor->ram;
|
||||
$flavors[$flavor->id]["disk"] = $flavor->disk;
|
||||
$flavors[$flavor->id]["vcpus"] = $flavor->vcpus;
|
||||
$flavors[$flavor->id]["links"] = $flavor->links;
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
$this->app->setOutput("Flavors", $flavors);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* List images.
|
||||
* @return array
|
||||
*/
|
||||
public function listImages()
|
||||
{
|
||||
$imageList = $this->libClass->listImages();
|
||||
$images = Array();
|
||||
foreach($imageList as $image){
|
||||
$images[$image->id] = Array();
|
||||
$image->retrieve();
|
||||
$images[$image->id]["id"] = $image->id;
|
||||
$images[$image->id]["name"] = $image->name;
|
||||
$images[$image->id]["status"] = $image->status;
|
||||
$images[$image->id]["created"] = $image->created;
|
||||
$images[$image->id]["updated"] = $image->updated;
|
||||
$images[$image->id]["minDisk"] = $image->minDisk;
|
||||
$images[$image->id]["minRam"] = $image->minRam;
|
||||
$images[$image->id]["progress"] = $image->progress;
|
||||
$images[$image->id]["links"] = $image->links;
|
||||
$images[$image->id]["metadata"] = $image->metadata;
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
$this->app->setOutput("Images", $images);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Get server details.
|
||||
* @return array
|
||||
*/
|
||||
public function getServer()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing, son!");
|
||||
return;
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->retrieve();
|
||||
$this->app->setOutput("MyServer", $server);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Get flavor details.
|
||||
* @return array
|
||||
*/
|
||||
public function getFlavor()
|
||||
{
|
||||
$flavorId = $this->app->getPostParam("flavorId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Flavor ID is missing, son!");
|
||||
return;
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
$opt = array('id' => $flavorId);
|
||||
$flavor = $this->libClass->getFlavor($opt);
|
||||
$flavor->retrieve();
|
||||
$this->app->setOutput("MyFlavor", $flavor);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Get image details.
|
||||
* @return array
|
||||
*/
|
||||
public function getImage()
|
||||
{
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Image ID is missing, son!");
|
||||
return;
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
$opt = array('id' => $imageId);
|
||||
$image = $this->libClass->getImage($opt);
|
||||
$image->retrieve();
|
||||
$this->app->setOutput("MyImage", $image);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Create server.
|
||||
* @return array
|
||||
*/
|
||||
public function createServer()
|
||||
{
|
||||
$name = $this->app->getPostParam("name");
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
$flavorId = $this->app->getPostParam("flavorId");
|
||||
if(!isset($name) || !isset($imageId) || !isset($flavorId)){
|
||||
$this->app->setOutput("Error", "No, we don't let you create a server without a name OR image ID OR flavor ID.");
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* List flavors.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function listFlavors()
|
||||
{
|
||||
try{
|
||||
$flavorList = $this->libClass->listFlavors();
|
||||
$flavors = Array();
|
||||
foreach($flavorList as $flavor){
|
||||
$flavors[$flavor->id] = Array();
|
||||
$flavor->retrieve();
|
||||
$flavors[$flavor->id]["id"] = $flavor->id;
|
||||
$flavors[$flavor->id]["name"] = $flavor->name;
|
||||
$flavors[$flavor->id]["ram"] = $flavor->ram;
|
||||
$flavors[$flavor->id]["disk"] = $flavor->disk;
|
||||
$flavors[$flavor->id]["vcpus"] = $flavor->vcpus;
|
||||
$flavors[$flavor->id]["links"] = $flavor->links;
|
||||
}
|
||||
$this->app->setOutput("Flavors", $flavors);
|
||||
}
|
||||
$opt = array('name' => $name, 'imageId' => $imageId, 'flavorId' => $flavorId);
|
||||
$server = $this->libClass->createServer($opt);
|
||||
}
|
||||
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List images.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function listImages()
|
||||
{
|
||||
try{
|
||||
$imageList = $this->libClass->listImages();
|
||||
$images = Array();
|
||||
foreach($imageList as $image){
|
||||
$images[$image->id] = Array();
|
||||
$image->retrieve();
|
||||
$images[$image->id]["id"] = $image->id;
|
||||
$images[$image->id]["name"] = $image->name;
|
||||
$images[$image->id]["status"] = $image->status;
|
||||
$images[$image->id]["created"] = $image->created;
|
||||
$images[$image->id]["updated"] = $image->updated;
|
||||
$images[$image->id]["minDisk"] = $image->minDisk;
|
||||
$images[$image->id]["minRam"] = $image->minRam;
|
||||
$images[$image->id]["progress"] = $image->progress;
|
||||
$images[$image->id]["links"] = $image->links;
|
||||
$images[$image->id]["metadata"] = $image->metadata;
|
||||
}
|
||||
$this->app->setOutput("Images", $images);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server details.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function getServer()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->retrieve();
|
||||
$this->app->setOutput("MyServer", $server);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get flavor details.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function getFlavor()
|
||||
{
|
||||
try{
|
||||
$flavorId = $this->app->getPostParam("flavorId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Flavor ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $flavorId);
|
||||
$flavor = $this->libClass->getFlavor($opt);
|
||||
$flavor->retrieve();
|
||||
$this->app->setOutput("MyFlavor", $flavor);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get image details.
|
||||
* @return array
|
||||
*/
|
||||
public function getImage()
|
||||
{
|
||||
try{
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Image ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $imageId);
|
||||
$image = $this->libClass->getImage($opt);
|
||||
$image->retrieve();
|
||||
$this->app->setOutput("MyImage", $image);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create server.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function createServer()
|
||||
{
|
||||
try{
|
||||
$name = $this->app->getPostParam("name");
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
$flavorId = $this->app->getPostParam("flavorId");
|
||||
if(!isset($name) || !isset($imageId) || !isset($flavorId)){
|
||||
$this->app->setOutput("Error", "Server name OR image ID OR flavor ID is missing.");
|
||||
return;
|
||||
}
|
||||
$opt = array('name' => $name, 'imageId' => $imageId, 'flavorId' => $flavorId);
|
||||
$server = $this->libClass->createServer($opt);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* update a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function updateServer()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$newName = $this->app->getPostParam("newName");
|
||||
$newIpv4 = $this->app->getPostParam("newIpv4");
|
||||
$newIpv6 = $this->app->getPostParam("newIpv6");
|
||||
if(!isset($serverId)|| !(isset($newName) || isset($newIpv4) || isset($newIpv6)) ){
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new attribute(IP(v4/v6)/Name) you desire to update!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
if (isset($newName)){
|
||||
if(isset($newIpv4)){
|
||||
if(isset($newIpv6)){
|
||||
$attr = array('name' => $newName, 'accessIPv4' => $newIPv4, 'accessIPv6' => $newIpv6);
|
||||
}
|
||||
else $attr = array('name' => $newName, 'accessIPv4' => $newIPv4);
|
||||
public function updateServer()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$newName = $this->app->getPostParam("newName");
|
||||
$newIpv4 = $this->app->getPostParam("newIpv4");
|
||||
$newIpv6 = $this->app->getPostParam("newIpv6");
|
||||
if(!isset($serverId)|| !(isset($newName) || isset($newIpv4) || isset($newIpv6)) ){
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new attribute(IP(v4/v6)/Name) you desire to update!");
|
||||
return;
|
||||
}
|
||||
else $attr = array('name' => $newName);
|
||||
}
|
||||
$server->update($attr);
|
||||
$this->app->setOutput("Success", $serverId." has been updated successfully.");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
if (isset($newName)){
|
||||
if(isset($newIpv4)){
|
||||
if(isset($newIpv6)){
|
||||
$attr = array('name' => $newName, 'accessIPv4' => $newIPv4, 'accessIPv6' => $newIpv6);
|
||||
}
|
||||
else $attr = array('name' => $newName, 'accessIPv4' => $newIPv4);
|
||||
}
|
||||
else $attr = array('name' => $newName);
|
||||
}
|
||||
$server->update($attr);
|
||||
$this->app->setOutput("Success", $serverId." has been updated successfully.");
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function deleteServer()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing, son!");
|
||||
return;
|
||||
public function deleteServer()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->delete();
|
||||
$this->app->setOutput("Success", $serverId." has been deleted successfully.");
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->delete();
|
||||
$this->app->setOutput("Success", $serverId." has been deleted successfully.");
|
||||
return;
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the password of a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function changePassword()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$password = $this->app->getPostParam("newPassword");
|
||||
if(!isset($serverId) || !isset($password)){
|
||||
$this->app->setOutput("Error", "Server ID or new password missing.");
|
||||
return;
|
||||
public function changePassword()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$password = $this->app->getPostParam("newPassword");
|
||||
if(!isset($serverId) || !isset($password)){
|
||||
$this->app->setOutput("Error", "Server ID or new password missing.");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->changePassword($password);
|
||||
$this->app->setOutput("Success", "Password for ".$serverId." has been updated successfully.");
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->changePassword($password);
|
||||
$this->app->setOutput("Success", "Password for ".$serverId." has been updated successfully.");
|
||||
return;
|
||||
}
|
||||
/**
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reboot a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reboot()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing, son!");
|
||||
return;
|
||||
public function reboot()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->reboot();
|
||||
$this->app->setOutput("Success", $serverId." has been deleted successfully.");
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->reboot();
|
||||
$this->app->setOutput("Success", $serverId." has been deleted successfully.");
|
||||
return;
|
||||
}
|
||||
/**
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function rebuild()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
$newName = $this->app->getPostParam("newName");
|
||||
$adminPass = $this->app->getPostParam("adminPass");
|
||||
public function rebuild()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
$newName = $this->app->getPostParam("newName");
|
||||
$adminPass = $this->app->getPostParam("adminPass");
|
||||
if(!isset($serverId)|| !isset($imageId) || isset($newName) || isset($adminPass)) {
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new image, name and admin password!");
|
||||
return;
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$imageId = $this->app->getPostParam("imageId");
|
||||
$newName = $this->app->getPostParam("newName");
|
||||
$adminPass = $this->app->getPostParam("adminPass");
|
||||
if(!isset($serverId)|| !isset($imageId) || isset($newName) || isset($adminPass)){
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new image, name and admin password!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$attr = array('imageId' => $imageId, 'name' => $newName, 'adminPass' => $adminPass);
|
||||
$server->rebuild($attr);
|
||||
$this->app->setOutput("Success", $serverId." has been rebuilt successfully with the new image.");
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$attr = array('imageId' => $imageId, 'name' => $newName, 'adminPass' => $adminPass);
|
||||
$server->rebuild($attr);
|
||||
$this->app->setOutput("Success", $serverId." has been rebuilt successfully with the new image.");
|
||||
return;
|
||||
}
|
||||
/**
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize a server
|
||||
*
|
||||
* A call to this method has to be followed by either confirmResize or revertResize
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function resize()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$newFlavorId = $this->app->getPostParam("newFlavorId");
|
||||
if(!isset($serverId)|| !isset($flavorId)){
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new flavor ID!");
|
||||
return;
|
||||
public function resize()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
$newFlavorId = $this->app->getPostParam("newFlavorId");
|
||||
if(!isset($serverId)|| !isset($flavorId)){
|
||||
$this->app->setOutput("Error", "You'll have to provide server ID and the new flavor ID!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->resize($newFlavorId);
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->resize($newFlavorId);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm resize operation on a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function confirmResize()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
public function confirmResize()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->confirmResize();
|
||||
$this->app->setOutput("Success", $serverId." has been resized successfully as the new flavor.");
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->confirmResize();
|
||||
$this->app->setOutput("Success", $serverId." has been resized successfully as the new flavor.");
|
||||
return;
|
||||
}
|
||||
/**
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Revert resize operation on a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function revertResize()
|
||||
{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
public function revertResize()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->revertResize();
|
||||
$this->app->setOutput("Success", $serverId." : resize operation has been reverted to the old flavor.");
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$server->revertResize();
|
||||
$this->app->setOutput("Success", $serverId." : resize operation has been reverted to the old flavor.");
|
||||
return;
|
||||
}
|
||||
/*
|
||||
public function createImage(array $options)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function listAddresses(array $options = [])
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function getMetadata()
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function resetMetadata(array $metadata)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function mergeMetadata(array $metadata)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function getMetadataItem($key)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
public function deleteMetadataItem($key)
|
||||
{
|
||||
//TODO
|
||||
}
|
||||
*/
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List private and public addresses of a server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function listAddresses()
|
||||
{
|
||||
try{
|
||||
$serverId = $this->app->getPostParam("serverId");
|
||||
if(!isset($serverId)){
|
||||
$this->app->setOutput("Error", "Server ID is missing!");
|
||||
return;
|
||||
}
|
||||
$opt = array('id' => $serverId);
|
||||
$server = $this->libClass->getServer($opt);
|
||||
$addresses = $server->listAddresses();
|
||||
$this->app->setOutput("Addresses", $addresses);
|
||||
}
|
||||
catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}
|
||||
catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}
|
||||
catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}
|
||||
catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}
|
||||
catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
19
server/core/CoreInterface.php
Normal file → Executable file
19
server/core/CoreInterface.php
Normal file → Executable file
|
@ -1,7 +1,26 @@
|
|||
<?php
|
||||
/**
|
||||
* File containing Core Interface.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Interface for the main classes of the API
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*/
|
||||
interface Core{
|
||||
|
||||
/**
|
||||
* Execute an action in the class
|
||||
*
|
||||
* @param String $action Function to be called
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function action($action);
|
||||
|
||||
}
|
|
@ -1,38 +1,126 @@
|
|||
<?php
|
||||
/**
|
||||
* File containing the errorManagement Class.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr', Evan Pisani 'yogg at epsina . com'
|
||||
*
|
||||
*/
|
||||
|
||||
use OpenCloud\Common\Error\BadResponseError;
|
||||
use OpenCloud\Common\Error\BaseError;
|
||||
use OpenCloud\Common\Error\NotImplementedError;
|
||||
use OpenCloud\Common\Error\UserInputError;
|
||||
|
||||
|
||||
/**
|
||||
* errorManagement Class of the back-end application
|
||||
*
|
||||
* Management of error
|
||||
*
|
||||
*/
|
||||
Class errorManagement{
|
||||
|
||||
/** @var App $app protected, contains the main app object */
|
||||
protected $app;
|
||||
|
||||
|
||||
/**
|
||||
* ErrorManagemement constructor
|
||||
*
|
||||
* @param App $args the main app object
|
||||
*
|
||||
* @return ErrorManagement Object
|
||||
*/
|
||||
public function __construct($args){
|
||||
|
||||
$this->app = $args;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Put an error message corresponding to a base error in the output
|
||||
*
|
||||
* @param Exception $error the exception triggered
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function BaseErrorHandler($error){
|
||||
|
||||
$this->app->setOutput("Error", "BaseError");
|
||||
}
|
||||
|
||||
/**
|
||||
* Put an error message corresponding to a bad response in function of the status code in the output
|
||||
*
|
||||
* @param Exception $error the exception triggered
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function BadResponseHandler($error){
|
||||
$this->app->setOutput("Error", "Erreur Interne, Merci de contacter un administrateur!");
|
||||
$statusCode = $error->getResponse()->getStatusCode();
|
||||
switch ($statusCode) {
|
||||
case 400:
|
||||
$this->app->setOutput("Error", "Invalid input.");
|
||||
break;
|
||||
|
||||
case 401:
|
||||
$this->app->setOutput("Error", "Authentification failed.");
|
||||
break;
|
||||
|
||||
case 403:
|
||||
$this->app->setOutput("Error", "Operation forbidden.");
|
||||
break;
|
||||
|
||||
case 404:
|
||||
$this->app->setOutput("Error", "Ressource not found.");
|
||||
break;
|
||||
|
||||
case 500:
|
||||
$this->app->setOutput("Error", "Internal server error, please contact an administrator.");
|
||||
break;
|
||||
|
||||
case 503:
|
||||
$this->app->setOutput("Error", "Service unvailable for the moment.");
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->app->setOutput("Error", "Unknow error, please contact an administrator.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put an error message corresponding to a not implemented yet error in the output
|
||||
*
|
||||
* @param Exception $error the exception triggered
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function NotImplementedHandler($error){
|
||||
$this->app->setOutput("Error", "Erreur Interne, Merci de contacter un administrateur!");
|
||||
$this->app->setOutput("Error", "Internal error (not implemented yet), please contact an administrator");
|
||||
}
|
||||
|
||||
/**
|
||||
* Put an error message corresponding to a user input error in the output
|
||||
*
|
||||
* @param Exception $error the exception triggered
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function UserInputHandler($error){
|
||||
|
||||
$this->app->setOutput("Error", "UserInputError");
|
||||
}
|
||||
|
||||
/**
|
||||
* Put an error message corresponding to an other error in the output
|
||||
*
|
||||
* @param Exception $error the exception triggered
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function OtherException($error){
|
||||
$this->app->setOutput("Error", $error->getMessage());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
@ -1,4 +1,14 @@
|
|||
<?php
|
||||
/**
|
||||
* File containing the override of the authentication for the Library.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*
|
||||
* @todo Check with the API, the condition and test the revoke token implementation
|
||||
*/
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use OpenCloud\Common\Transport\HandlerStack;
|
||||
|
@ -9,47 +19,83 @@ use OpenCloud\Common\Auth\Token;
|
|||
use OpenCloud\Common\Transport\Utils;
|
||||
use OpenStack\Identity\v3\Models;
|
||||
|
||||
/**
|
||||
* genTokenOptions Class
|
||||
*
|
||||
* This class allow the generation of tokens for openstack, and to inject
|
||||
* those tokens into the library. Which allow to do a proper login only once
|
||||
* and not for each request
|
||||
*
|
||||
*/
|
||||
class genTokenOptions
|
||||
{
|
||||
/** @var Array $optionsGlobal private, contains the options common for the different tokens */
|
||||
private $optionsGlobal;
|
||||
|
||||
private $stack;
|
||||
/** @var Array $backup private, contains all the informations about the different tokens. It contains the information send to the clients */
|
||||
private $backup = [];
|
||||
/** @var GuzzleHttp\Client $httpClient private, contains a default Client to construct some OpenStack library object */
|
||||
private $httpClient;
|
||||
|
||||
/**
|
||||
* genTokenOptions constructor
|
||||
*
|
||||
* @param Array $options Options to create the objects in the library
|
||||
* AuthUrl is the main options required
|
||||
*
|
||||
* @return genTokenOptions Object
|
||||
*/
|
||||
public function __construct($options){
|
||||
|
||||
$this->stack = HandlerStack::create();
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
$httpClient = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($options['authUrl']),
|
||||
'handler' => $this->stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($options['authUrl']),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
|
||||
$this->httpClient = $httpClient;
|
||||
|
||||
$options['identityService'] = Service::factory($httpClient);
|
||||
$options['identityService'] = Service::factory($httpClient);
|
||||
|
||||
$options['authHandler'] = function () use ($options) {
|
||||
return $options['identityService']->generateToken($options);
|
||||
};
|
||||
};
|
||||
|
||||
$this->optionsGlobal['Common'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
private function addDebugMiddleware(array $options, HandlerStack &$stack)
|
||||
{
|
||||
if (!empty($options['debugLog'])
|
||||
&& !empty($options['logger'])
|
||||
&& !empty($options['messageFormatter'])
|
||||
) {
|
||||
$stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a debug for the library
|
||||
*
|
||||
* @param array $options Debug options, cf library
|
||||
* @param HandlerStack $stack pointer to a HandlerStack object
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function addDebugMiddleware(array $options, HandlerStack &$stack)
|
||||
{
|
||||
if (!empty($options['debugLog'])
|
||||
&& !empty($options['logger'])
|
||||
&& !empty($options['messageFormatter'])
|
||||
) {
|
||||
$stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the expiration time of a token
|
||||
*
|
||||
* @return boolean if the token is not expired
|
||||
*/
|
||||
public function checkToken(){
|
||||
return $this->backup['time'] > time();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new token for the Identity service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function genIdentityToken(){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'false';
|
||||
|
@ -67,20 +113,32 @@ class genTokenOptions
|
|||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Identity', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
|
||||
$this->optionsGlobal['Identity'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token for the Identity Service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function revokeIdentityToken(){
|
||||
$token = $this->unserializeToken($this->backup['Identity']['token']);
|
||||
$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a token for the Identity Service
|
||||
*
|
||||
* @param String $opt serialized token
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function loadIdentityBackup($opt){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'false';
|
||||
|
@ -92,20 +150,25 @@ class genTokenOptions
|
|||
$baseUrl = $this->backup['Identity']['baseUrl'];
|
||||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Identity', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
$this->optionsGlobal['Identity'] = $options;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new token for the Image service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function genImageToken(){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'glance';
|
||||
|
@ -116,25 +179,37 @@ class genTokenOptions
|
|||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Image', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
|
||||
$this->optionsGlobal['Image'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token for the Image Service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function revokeImageToken(){
|
||||
$token = $this->unserializeToken($this->backup['Image']['token']);
|
||||
$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a token for the Image Service
|
||||
*
|
||||
* @param String $opt serialized token
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function loadImageBackup($opt){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'glance';
|
||||
|
@ -144,7 +219,7 @@ class genTokenOptions
|
|||
$this->backup['Image'] = $opt;
|
||||
$token = $this->unserializeToken($this->backup['Image']['token']);
|
||||
$baseUrl = $this->backup['Image']['baseUrl'];
|
||||
|
||||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
@ -152,13 +227,18 @@ class genTokenOptions
|
|||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Image', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
$this->optionsGlobal['Image'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new token for the Metwork service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function genNetworkToken(){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'neutron';
|
||||
|
@ -169,25 +249,37 @@ class genTokenOptions
|
|||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Network', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
|
||||
$this->optionsGlobal['Network'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token for the Network Service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function revokeNetworkToken(){
|
||||
$token = $this->unserializeToken($this->backup['Network']['token']);
|
||||
$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a token for the Network Service
|
||||
*
|
||||
* @param String $opt serialized token
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function loadNetworkBackup($opt){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'neutron';
|
||||
|
@ -197,21 +289,26 @@ class genTokenOptions
|
|||
$this->backup['Network'] = $opt;
|
||||
$token = $this->unserializeToken($this->backup['Network']['token']);
|
||||
$baseUrl = $this->backup['Network']['baseUrl'];
|
||||
|
||||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Network', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
$this->optionsGlobal['Network'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new token for the Compute service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function genComputeToken(){
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
$options['catalogName'] = 'nova';
|
||||
|
@ -222,25 +319,37 @@ class genTokenOptions
|
|||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Compute', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
|
||||
$this->optionsGlobal['Compute'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token for the Compute Service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function revokeComputeToken(){
|
||||
$token = $this->unserializeToken($this->backup['Compute']['token']);
|
||||
$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a token for the Compute Service
|
||||
*
|
||||
* @param String $opt serialized token
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function loadComputeBackup($opt){
|
||||
|
||||
$options = $this->optionsGlobal['Common'];
|
||||
|
@ -251,40 +360,61 @@ class genTokenOptions
|
|||
$this->backup['Compute'] = $opt;
|
||||
$token = $this->unserializeToken($this->backup['Compute']['token']);
|
||||
$baseUrl = $this->backup['Compute']['baseUrl'];
|
||||
|
||||
|
||||
$stack = HandlerStack::create();
|
||||
|
||||
|
||||
$stack->push(Middleware::authHandler($options['authHandler'], $token));
|
||||
|
||||
$this->addDebugMiddleware($options, $stack);
|
||||
|
||||
$options['httpClient'] = new Client([
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
'base_uri' => Utils::normalizeUrl($baseUrl),
|
||||
'handler' => $stack,
|
||||
]);
|
||||
$this->saveBackup('Compute', array('token' => $token, 'baseUrl' => $baseUrl ));
|
||||
$this->optionsGlobal['Compute'] = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the token given a service name
|
||||
*
|
||||
* @param String $name name of the service to save
|
||||
* @param Array $data token and baseUrl for the service
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function saveBackup($name, $data){
|
||||
$token = $this->serializeToken($data["token"]);
|
||||
$path = "core/LibOverride/projectTokenData/".$token['saved']["project"]["name"];
|
||||
//error_log(print_r($path, true), 0);
|
||||
file_put_contents("core/LibOverride/projectTokenData/".$token['saved']["project"]["name"], serialize($token['saved']));
|
||||
$ret = file_put_contents("core/LibOverride/projectTokenData/".$token['saved']["project"]["name"], serialize($token['saved']));
|
||||
if($ret === FALSE)
|
||||
die("Internal Server Error : File Rights");
|
||||
$this->backup['time'] = $token['time'];
|
||||
$this->backup["roles"] = $token["roles"];
|
||||
$this->backup["project"] = $token['saved']["project"]["name"];
|
||||
$this->backup["user"] = $token["user"];
|
||||
$this->backup[$name] = array('token' => $token["token"], 'baseUrl' => $data["baseUrl"] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the tokens saved
|
||||
*
|
||||
* @return String tokens serialized
|
||||
*/
|
||||
public function getBackup(){
|
||||
return serialize($this->backup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load tokens into the library
|
||||
*
|
||||
* @param String $back tokens serialized
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function loadBackup($back){
|
||||
|
||||
$backup = unserialize($back);
|
||||
|
||||
$this->backup['time'] = $backup['time'];
|
||||
$this->backup["roles"] = $backup["roles"];
|
||||
$this->backup["project"] = $backup["project"];
|
||||
$this->backup["user"] = $backup["user"];
|
||||
|
@ -295,18 +425,33 @@ class genTokenOptions
|
|||
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the common options for a service
|
||||
*
|
||||
* @param String $service name of the service
|
||||
*
|
||||
* @return array Options to create the library class corresponding to this service
|
||||
*/
|
||||
public function getOptions($service){
|
||||
return $this->optionsGlobal[$service];
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a given token
|
||||
*
|
||||
* @param Array $token token to be serialized
|
||||
*
|
||||
* @return String token serialized
|
||||
*/
|
||||
private function serializeToken($token){
|
||||
global $config;
|
||||
$tokenSerialized = [];
|
||||
$tokenSerialized["token"]["methods"] = serialize($token->methods);
|
||||
$tokenSerialized["roles"] = [];
|
||||
|
||||
|
||||
foreach($token->roles as $role){
|
||||
$tokenSerialized["roles"][serialize($role->id)]["links"] = serialize($role->links);
|
||||
$tokenSerialized["roles"][serialize($role->id)]["name"] = serialize($role->name);
|
||||
$tokenSerialized["roles"][$role->id]["links"] = serialize($role->links);
|
||||
$tokenSerialized["roles"][$role->id]["name"] = serialize($role->name);
|
||||
}
|
||||
|
||||
$tokenSerialized["token"]["expires"] = serialize($token->expires);
|
||||
|
@ -318,19 +463,21 @@ class genTokenOptions
|
|||
$tokenSerialized['saved']["project"]["links"] = serialize($token->project->links);
|
||||
$tokenSerialized['saved']["project"]["name"] = $token->project->name;
|
||||
|
||||
$tokenSerialized['saved']["catalog"] = array();
|
||||
foreach($token->catalog->services as $service){
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["name"] = serialize($service->name);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["description"] = serialize($service->description);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["type"] = serialize($service->type);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["name"] = serialize($service->name);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["description"] = serialize($service->description);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["type"] = serialize($service->type);
|
||||
|
||||
foreach($service->endpoints as $end){
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["interface"] = serialize($end->interface);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["name"] = serialize($end->name);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["serviceId"] = serialize($end->serviceId);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["region"] = serialize($end->region);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["links"] = serialize($end->links);
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["url"] = serialize($end->url);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["interface"] = serialize($end->interface);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["name"] = serialize($end->name);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["serviceId"] = serialize($end->serviceId);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["region"] = serialize($end->region);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["links"] = serialize($end->links);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["url"] = serialize($end->url);
|
||||
}
|
||||
$tokenSerialized['saved']["catalog"][serialize($service->id)]["links"] = serialize($service->links);
|
||||
$tokenSerialized['saved']["catalog"][$service->id]["links"] = serialize($service->links);
|
||||
}
|
||||
$tokenSerialized["token"]["extras"] = serialize($token->extras);
|
||||
$tokenSerialized["user"]["domainId"] = serialize($token->user->domainId);
|
||||
|
@ -343,22 +490,35 @@ class genTokenOptions
|
|||
$tokenSerialized["user"]["name"] = serialize($token->user->name);
|
||||
$tokenSerialized["token"]["issued"] = serialize($token->issued);
|
||||
$tokenSerialized["token"]["id"] = serialize($token->id);
|
||||
$tokenSerialized['time'] = time()+$config['tokenTime']*60;
|
||||
|
||||
return $tokenSerialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize a token
|
||||
*
|
||||
* Unserialize a token and recreate the architecture of the library token
|
||||
*
|
||||
* @param String $tokenSerialized the token to be unserialized
|
||||
*
|
||||
* @return OpenCloud\Common\Auth\Token the token unserialized
|
||||
*/
|
||||
private function unserializeToken($tokenSerialized){
|
||||
$Saved = file_get_contents("core/LibOverride/projectTokenData/".$this->backup["project"]);
|
||||
if($Saved === FALSE)
|
||||
die("Internal Server Error : File Access");
|
||||
$Saved = unserialize($Saved);
|
||||
|
||||
$api = new Api();
|
||||
$token = new Models\Token($this->httpClient, $api);
|
||||
$token->methods = unserialize($tokenSerialized["methods"]);
|
||||
$token->roles = [];
|
||||
|
||||
|
||||
foreach($this->backup["roles"] as $key => $role){
|
||||
$tmp = new Models\Role($this->httpClient, $api);
|
||||
|
||||
$tmp->id = unserialize($key);
|
||||
$tmp->id = $key;
|
||||
$tmp->links = unserialize($role["links"]);
|
||||
$tmp->name = unserialize($role["name"]);
|
||||
|
||||
|
@ -377,17 +537,19 @@ class genTokenOptions
|
|||
|
||||
$token->catalog = new Models\Catalog($this->httpClient, $api);
|
||||
$token->catalog->services = [];
|
||||
|
||||
foreach($Saved["catalog"] as $key => $service){
|
||||
$tmp = new Models\Service($this->httpClient, $api);
|
||||
|
||||
$tmp->id = unserialize($key);
|
||||
$tmp->id = $key;
|
||||
$tmp->name = unserialize($service["name"]);
|
||||
$tmp->description = unserialize($service["description"]);
|
||||
$tmp->type = unserialize($service["type"]);
|
||||
$tmp->endpoints = [];
|
||||
|
||||
foreach($service["endpoints"] as $key => $end){
|
||||
$tmpEnd = new Models\Endpoint($this->httpClient, $api);
|
||||
$tmpEnd->id = unserialize($key);
|
||||
$tmpEnd->id = $key;
|
||||
$tmpEnd->interface = unserialize($end["interface"]);
|
||||
$tmpEnd->name = unserialize($end["name"]);
|
||||
$tmpEnd->serviceId = unserialize($end["serviceId"]);
|
||||
|
@ -412,7 +574,7 @@ class genTokenOptions
|
|||
$token->user->description = unserialize($this->backup["user"]["description"]);
|
||||
$token->issued = unserialize($tokenSerialized["issued"]);
|
||||
$token->id = unserialize($tokenSerialized["id"]);
|
||||
|
||||
|
||||
return $token;
|
||||
}
|
||||
}
|
||||
|
|
0
server/core/LibOverride/projectTokenData/demo
Normal file → Executable file
0
server/core/LibOverride/projectTokenData/demo
Normal file → Executable file
1280
server/core/Network.php
Normal file → Executable file
1280
server/core/Network.php
Normal file → Executable file
File diff suppressed because it is too large
Load diff
531
server/core/NetworkLayer3.php
Executable file
531
server/core/NetworkLayer3.php
Executable file
|
@ -0,0 +1,531 @@
|
|||
<?php
|
||||
/**
|
||||
* File containing the networkLayer3 Class.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Evan Pisani 'yogg at epsina . com'
|
||||
*
|
||||
*/
|
||||
|
||||
use OpenCloud\Common\Error\BadResponseError;
|
||||
use OpenCloud\Common\Error\BaseError;
|
||||
use OpenCloud\Common\Error\NotImplementedError;
|
||||
use OpenCloud\Common\Error\UserInputError;
|
||||
|
||||
include("CoreInterface.php");
|
||||
|
||||
/**
|
||||
* networkLayer3 Class of the back-end application
|
||||
*
|
||||
* Management of networkLayer3
|
||||
*
|
||||
*/
|
||||
class networkLayer3 implements Core{
|
||||
|
||||
/** @var App $app protected, contains the main app object */
|
||||
protected $app;
|
||||
|
||||
/** @var OpenStack\NetworkLayer3 $libClass protected, contains the library NetworkLayer3 object */
|
||||
protected $libClass;
|
||||
|
||||
/**
|
||||
* networkLayer3 constructor
|
||||
*
|
||||
* @param App $app the main app object
|
||||
*
|
||||
* @return networkLayer3 Object
|
||||
*/
|
||||
public function __construct($app){
|
||||
if(!isset($app)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter app");
|
||||
}
|
||||
$this->app = $app;
|
||||
$this->libClass = $app->getLibClass("NetworkLayer3");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Execute an action
|
||||
*
|
||||
* @param String $action name of another function of this class
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function action($action){
|
||||
$this->{$action.""}();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* List floatingip
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function listFloatingIp(){
|
||||
try{
|
||||
$result = array();
|
||||
$l = $this->libClass->listFloatingIps();
|
||||
error_log(var_export($l, true), 0);
|
||||
foreach ($l as $tmp) {
|
||||
$result[] = $tmp;
|
||||
}
|
||||
|
||||
$this->app->setOutput("NetworkLayer3", $result);
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new floating IP adress
|
||||
*
|
||||
* @param array $opt Options for the floating ip creation (floatingNetworkId is required)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function createFloatingIp(){
|
||||
$opt = $this->app->getPostParam("opt");
|
||||
|
||||
if(!isset($opt)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
$floatingip = $this->libClass->createFloatingIp($opt);
|
||||
|
||||
if(!isset($floatingip)){
|
||||
$this->app->setOutput("Error", "Unknowing error during floating ip creation");
|
||||
}else{
|
||||
$this->app->setOutput("NetworkLayer3", $floatingip);
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Show floatingip details
|
||||
*
|
||||
* @param String id the id of the floatingip
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function getFloatingIp(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
|
||||
try{
|
||||
// List of floating IPs
|
||||
$res = array();
|
||||
$l = $this->libClass->listFloatingIps();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknow id");
|
||||
}else{ // If id exists
|
||||
$res = $this->libClass->getFloatingIp($id);
|
||||
$this->app->setOutput("NetworkLayer3", $res);
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update floating ip
|
||||
*
|
||||
* @param id the id of the floatingip to update
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function updateFloatingIp(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
|
||||
// List of floating IPs
|
||||
$res = array();
|
||||
$l = $this->libClass->listFloatingIps();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknowing floatingip id");
|
||||
}else{
|
||||
$result->update();
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a floating ip
|
||||
*
|
||||
* @param string floatingip_id the floating-ip id to delete
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function deleteFloatingIp(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
// List of floating IPs
|
||||
$res = array();
|
||||
$l = $this->libClass->listFloatingIps();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknowing floatingip id");
|
||||
}else{
|
||||
$result->delete();
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve a floating ip
|
||||
*
|
||||
* @param string floatingip_id the floating-ip id to retrieve
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function retrieveFloatingIp(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
// List of floating IPs
|
||||
$res = array();
|
||||
$l = $this->libClass->listFloatingIps();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknowing floatingip id");
|
||||
}else{
|
||||
$result->retrieve();
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Create a new router
|
||||
*
|
||||
* @param array $opt Options for the new router
|
||||
* externalGatewayInfo[] required (only the param networkId in the tab)
|
||||
* adminStateUp (optionnal)
|
||||
* name (optionnal)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function createRouter(){
|
||||
$opt = $this->app->getPostParam("opt");
|
||||
|
||||
if(!isset($opt)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
$router = $this->libClass->createRouter($opt);
|
||||
|
||||
if(!isset($router)){
|
||||
$this->app->setOutput("Error", "Unknowing error during floating ip creation");
|
||||
}else{
|
||||
$this->app->setOutput("NetworkLayer3", $router);
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* List routers
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function listRouters(){
|
||||
try{
|
||||
$result = array();
|
||||
$l = $this->libClass->listRouters();
|
||||
foreach ($l as $tmp) {
|
||||
$result[] = $tmp;
|
||||
}
|
||||
|
||||
$this->app->setOutput("NetworkLayer3", $result);
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Show router details
|
||||
*
|
||||
* @param String id the id of the router
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function getRouter(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
// List of routers
|
||||
$res = array();
|
||||
$l = $this->libClass->listRouters();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknow id");
|
||||
}else{ // If id exists
|
||||
$res = $this->libClass->getRouter($id);
|
||||
$this->app->setOutput("NetworkLayer3", $res);
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Delete a router
|
||||
*
|
||||
* @param string router the router to delete
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function deleteRouter(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
// List of routers
|
||||
$res = array();
|
||||
$l = $this->libClass->listRouters();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknowing router id");
|
||||
}else{
|
||||
$result->delete();
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update router
|
||||
*
|
||||
* @param id the id of the floatingip to update
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function updateRouter(){
|
||||
$id = $this->app->getPostParam("id");
|
||||
|
||||
if(!isset($id)){
|
||||
$this->app->setOutput("Error", "Incorrect parameter opt");
|
||||
}
|
||||
try{
|
||||
|
||||
// List of floating IPs
|
||||
$res = array();
|
||||
$l = $this->libClass->listRouters();
|
||||
foreach ($l as $tmp) {
|
||||
$res[] = $tmp;
|
||||
}
|
||||
|
||||
// Verification if id exists
|
||||
$result = null;
|
||||
foreach ($res as $f) {
|
||||
if(strcmp($f->id, $id)){
|
||||
$result = $f;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($result)){ // If id doesn't exists
|
||||
$this->app->setOutput("Error", "Unknowing floatingip id");
|
||||
}else{
|
||||
$result->update();
|
||||
}
|
||||
}catch(BadResponseError $e){
|
||||
$this->app->getErrorInstance()->BadResponseHandler($e);
|
||||
}catch(UserInputError $e){
|
||||
$this->app->getErrorInstance()->UserInputHandler($e);
|
||||
}catch(BaseError $e){
|
||||
$this->app->getErrorInstance()->BaseErrorHandler($e);
|
||||
}catch(NotImplementedError $e){
|
||||
$this->app->getErrorInstance()->NotImplementedHandler($e);
|
||||
}catch(Exception $e){
|
||||
$this->app->getErrorInstance()->OtherException($e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
<?php
|
||||
|
||||
abstract class plugin{
|
||||
|
||||
public $api;
|
||||
|
||||
public function __construct($api){
|
||||
|
||||
$this->api = $api;
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
<?php
|
||||
|
||||
//Init plugin directory
|
||||
/*if (!defined('PLUGINS_DIR')) {
|
||||
define('PLUGINS_DIR', INSTALL_PATH . 'plugins/');
|
||||
}*/
|
||||
|
||||
class plugin_api{
|
||||
|
||||
static protected $instance;
|
||||
|
||||
protected function __construct(){
|
||||
|
||||
}
|
||||
|
||||
static function getInstance(){
|
||||
|
||||
if(!self::$instance){
|
||||
self::$instance = new plugin_api();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
}
|
0
server/core/Readme.txt
Normal file → Executable file
0
server/core/Readme.txt
Normal file → Executable file
|
@ -1,55 +0,0 @@
|
|||
<?php
|
||||
|
||||
ini_set('display_errors', 1);
|
||||
date_default_timezone_set("Europe/Paris");
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
$options = Array();
|
||||
$options["user"] = Array("name"=>"admin", "password"=>"ae5or6cn", "domain"=>["id"=>"Default"]);
|
||||
$options["scope"] = Array("project"=>Array("name"=>"admin", "domain"=>["id"=>"Default"]));
|
||||
$options["authUrl"] = "http://148.60.11.31:5000/v3";
|
||||
$openstack = new OpenStack\OpenStack($options);
|
||||
$compute=$openstack->computeV2(["region" => "RegionOne"]);
|
||||
$servers = $compute->listServers(true);
|
||||
foreach($servers as $server)
|
||||
{
|
||||
$monserv = $server;
|
||||
echo $server->name."<br>";
|
||||
}
|
||||
echo "<br><br>";
|
||||
|
||||
$images = $compute->ListImages();
|
||||
|
||||
$monim = "";
|
||||
foreach($images as $image)
|
||||
{
|
||||
|
||||
|
||||
$monim = $image;
|
||||
echo $image->name."<br>";
|
||||
break;
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
$flavors = $compute->ListFlavors();
|
||||
|
||||
echo "<br><br>";
|
||||
|
||||
$monflav = "";
|
||||
|
||||
foreach($flavors as $flavor)
|
||||
{
|
||||
|
||||
$monflav=$flavor;
|
||||
echo $flavor->name."<br>";
|
||||
break;
|
||||
}
|
||||
|
||||
$response= $compute->createServer(array('name' => "TestOthmane2",'imageId' => $monim->id , 'flavorId'=>$monflav->id , "networks" => array
|
||||
( array("uuid"=> "251b4641-20ff-4a72-8549-1758788b51ce"))));
|
||||
|
||||
|
||||
|
142
server/index.php
142
server/index.php
|
@ -1,60 +1,90 @@
|
|||
<?php
|
||||
require "vendor/autoload.php";
|
||||
include_once("config.inc.php");
|
||||
include_once("init.php");
|
||||
/**
|
||||
* File containing the code for the API door.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
*/
|
||||
//loading dependencies
|
||||
require "vendor/autoload.php";
|
||||
//Include general config file
|
||||
include_once("config.inc.php");
|
||||
//Include API initialisation
|
||||
include_once("init.php");
|
||||
|
||||
if(isset($_POST["task"]) && isset($_POST["action"])){
|
||||
$task = $_POST["task"];
|
||||
$action = $_POST["action"];
|
||||
}else if(isset($_POST["task"]) && $_POST["task"] == "Authenticate" || $_POST["task"] == "Deauthenticate"){
|
||||
$task = $_POST["task"];
|
||||
}else{
|
||||
$App->setOutput("Error", "Invalid Request!");
|
||||
$App->show();
|
||||
exit();
|
||||
}
|
||||
|
||||
//Authentification and deauthentification request
|
||||
if($task == "Authenticate"){
|
||||
|
||||
if(isset($_POST["task"]) && isset($_POST["action"])){
|
||||
$task = $_POST["task"];
|
||||
$action = $_POST["action"];
|
||||
}else if(isset($_POST["task"]) && $_POST["task"] == "Authenticate" || $_POST["task"] == "Deauthenticate"){
|
||||
$task = $_POST["task"];
|
||||
}else{
|
||||
//Gestion Erreur
|
||||
$App->authenticate();
|
||||
$App->show();
|
||||
|
||||
}else if($task == "Deauthenticate"){
|
||||
|
||||
$App->deauthenticate();
|
||||
$App->show();
|
||||
|
||||
}else if($App->checkToken()){
|
||||
//Task switcher and task's file loader
|
||||
switch($task)
|
||||
{
|
||||
case "identity":
|
||||
include_once("core/Identity.php");
|
||||
$identityObject = new identity($App);
|
||||
$identityObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "network":
|
||||
include_once("core/Network.php");
|
||||
$networkObject = new network($App);
|
||||
$networkObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "image":
|
||||
include_once("core/Image.php");
|
||||
$imageObject = new image($App);
|
||||
$imageObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "compute":
|
||||
include_once("core/Compute.php");
|
||||
$computeObject = new compute($App);
|
||||
$computeObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "networkLayer3":
|
||||
include_once("core/NetworkLayer3.php");
|
||||
$computeObject = new networkLayer3($App);
|
||||
$computeObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
}
|
||||
|
||||
if($task == "Authenticate"){
|
||||
|
||||
$App->authenticate();
|
||||
$App->show();
|
||||
|
||||
}else if($task == "Deauthenticate"){
|
||||
|
||||
$App->deauthenticate();
|
||||
$App->show();
|
||||
|
||||
}else{
|
||||
switch($task)
|
||||
{
|
||||
case "identity":
|
||||
include_once("core/Identity.php");
|
||||
$identityObject = new identity($App);
|
||||
$identityObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "network":
|
||||
include_once("core/Network.php");
|
||||
$networkObject = new network($App);
|
||||
$networkObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "image":
|
||||
include_once("core/Image.php");
|
||||
$imageObject = new image($App);
|
||||
$imageObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
|
||||
case "compute":
|
||||
include_once("core/Compute.php");
|
||||
$computeObject = new compute($App);
|
||||
$computeObject->action($action);
|
||||
$App->show();
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}else{
|
||||
//Request without authentication
|
||||
$App->setOutput("Error", "Token Invalide");
|
||||
$App->show();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,48 +1,58 @@
|
|||
<?php
|
||||
include_once("core/App.php");
|
||||
/**
|
||||
* File containing the initialisation of the API.
|
||||
*
|
||||
* @version 1.0 Initialisation of this file
|
||||
* @since 1.0 Core application's file
|
||||
*
|
||||
* @author Eole 'eoledev at outlook . fr'
|
||||
*
|
||||
*/
|
||||
|
||||
$user = "";
|
||||
$password = "";
|
||||
$project = "";
|
||||
|
||||
|
||||
//traitement requete, recuperation data
|
||||
if(isset($_POST["token"])){
|
||||
|
||||
$token = $_POST["token"];
|
||||
|
||||
}else if(isset($_POST["user"]) && isset($_POST["password"]) && isset($_POST["project"]) ){
|
||||
|
||||
$user = $_POST["user"];
|
||||
$password = $_POST["password"];
|
||||
$project = $_POST["project"];
|
||||
|
||||
} /*else { // Test Backend
|
||||
$user = "admin";
|
||||
$password = "ae5or6cn";
|
||||
$project = "admin";
|
||||
|
||||
}*/
|
||||
/*
|
||||
* Include Main Api Class
|
||||
*/
|
||||
include_once("core/App.php");
|
||||
|
||||
$Args = Array(
|
||||
"user" => Array(
|
||||
"name" => $user,
|
||||
"password" => $password,
|
||||
"domain" => Array(
|
||||
"name" => "Default")
|
||||
),
|
||||
"scope" => Array(
|
||||
"project" => Array(
|
||||
"name" => $project,
|
||||
"domain" => Array(
|
||||
"name" => "Default")
|
||||
)
|
||||
),
|
||||
"authUrl" => $config["urlAuth"]
|
||||
);
|
||||
|
||||
$App = new App($Args);
|
||||
$user = "";
|
||||
$password = "";
|
||||
$project = "";
|
||||
|
||||
if(isset($token))
|
||||
$App->setToken($token);
|
||||
|
||||
//token processing
|
||||
if(isset($_POST["token"])){
|
||||
|
||||
$token = $_POST["token"];
|
||||
|
||||
}else if(isset($_POST["user"]) && isset($_POST["password"]) && isset($_POST["project"]) ){
|
||||
|
||||
$user = $_POST["user"];
|
||||
$password = $_POST["password"];
|
||||
$project = $_POST["project"];
|
||||
|
||||
}
|
||||
|
||||
//Library args
|
||||
$Args = Array(
|
||||
"user" => Array(
|
||||
"name" => $user,
|
||||
"password" => $password,
|
||||
"domain" => Array(
|
||||
"name" => "Default")
|
||||
),
|
||||
"scope" => Array(
|
||||
"project" => Array(
|
||||
"name" => $project,
|
||||
"domain" => Array(
|
||||
"name" => "Default")
|
||||
)
|
||||
),
|
||||
"authUrl" => $config["urlAuth"]
|
||||
);
|
||||
|
||||
//Init core Api
|
||||
$App = new App($Args);
|
||||
|
||||
if(isset($token))
|
||||
$App->setToken($token);
|
||||
?>
|
||||
|
|
0
server/modules/Readme.txt
Normal file → Executable file
0
server/modules/Readme.txt
Normal file → Executable file
7
server/vendor/autoload.php
vendored
7
server/vendor/autoload.php
vendored
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload.php @generated by Composer
|
||||
|
||||
require_once __DIR__ . '/composer' . '/autoload_real.php';
|
||||
|
||||
return ComposerAutoloaderInit6278e204890e617cb73cd66b51c1141f::getLoader();
|
1
server/vendor/bin/validate-json
vendored
1
server/vendor/bin/validate-json
vendored
|
@ -1 +0,0 @@
|
|||
../justinrainbow/json-schema/bin/validate-json
|
413
server/vendor/composer/ClassLoader.php
vendored
413
server/vendor/composer/ClassLoader.php
vendored
|
@ -1,413 +0,0 @@
|
|||
<?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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
// work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
|
||||
if ('\\' == $class[0]) {
|
||||
$class = substr($class, 1);
|
||||
}
|
||||
|
||||
// class map lookup
|
||||
if (isset($this->classMap[$class])) {
|
||||
return $this->classMap[$class];
|
||||
}
|
||||
if ($this->classMapAuthoritative) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$file = $this->findFileWithExtension($class, '.php');
|
||||
|
||||
// Search for Hack files if we are running on HHVM
|
||||
if ($file === null && defined('HHVM_VERSION')) {
|
||||
$file = $this->findFileWithExtension($class, '.hh');
|
||||
}
|
||||
|
||||
if ($file === null) {
|
||||
// Remember that this class does not exist.
|
||||
return $this->classMap[$class] = false;
|
||||
}
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
private function findFileWithExtension($class, $ext)
|
||||
{
|
||||
// PSR-4 lookup
|
||||
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
|
||||
|
||||
$first = $class[0];
|
||||
if (isset($this->prefixLengthsPsr4[$first])) {
|
||||
foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
|
||||
if (0 === strpos($class, $prefix)) {
|
||||
foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope isolated include.
|
||||
*
|
||||
* Prevents access to $this/self from included files.
|
||||
*/
|
||||
function includeFile($file)
|
||||
{
|
||||
include $file;
|
||||
}
|
21
server/vendor/composer/LICENSE
vendored
21
server/vendor/composer/LICENSE
vendored
|
@ -1,21 +0,0 @@
|
|||
|
||||
Copyright (c) 2015 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.
|
||||
|
9
server/vendor/composer/autoload_classmap.php
vendored
9
server/vendor/composer/autoload_classmap.php
vendored
|
@ -1,9 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload_classmap.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(dirname(__FILE__));
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
);
|
12
server/vendor/composer/autoload_files.php
vendored
12
server/vendor/composer/autoload_files.php
vendored
|
@ -1,12 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload_files.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(dirname(__FILE__));
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php',
|
||||
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
|
||||
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
|
||||
);
|
|
@ -1,9 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload_namespaces.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(dirname(__FILE__));
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
);
|
18
server/vendor/composer/autoload_psr4.php
vendored
18
server/vendor/composer/autoload_psr4.php
vendored
|
@ -1,18 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload_psr4.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(dirname(__FILE__));
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
|
||||
'OpenStack\\' => array($vendorDir . '/php-opencloud/openstack/src'),
|
||||
'OpenCloud\\Test\\' => array($vendorDir . '/php-opencloud/common/tests/unit'),
|
||||
'OpenCloud\\Integration\\' => array($vendorDir . '/php-opencloud/common/tests/integration'),
|
||||
'OpenCloud\\' => array($vendorDir . '/php-opencloud/common/src'),
|
||||
'JsonSchema\\' => array($vendorDir . '/justinrainbow/json-schema/src/JsonSchema'),
|
||||
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
|
||||
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
|
||||
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
|
||||
);
|
59
server/vendor/composer/autoload_real.php
vendored
59
server/vendor/composer/autoload_real.php
vendored
|
@ -1,59 +0,0 @@
|
|||
<?php
|
||||
|
||||
// autoload_real.php @generated by Composer
|
||||
|
||||
class ComposerAutoloaderInit6278e204890e617cb73cd66b51c1141f
|
||||
{
|
||||
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('ComposerAutoloaderInit6278e204890e617cb73cd66b51c1141f', 'loadClassLoader'), true, true);
|
||||
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
|
||||
spl_autoload_unregister(array('ComposerAutoloaderInit6278e204890e617cb73cd66b51c1141f', 'loadClassLoader'));
|
||||
|
||||
$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);
|
||||
|
||||
$includeFiles = require __DIR__ . '/autoload_files.php';
|
||||
foreach ($includeFiles as $fileIdentifier => $file) {
|
||||
composerRequire6278e204890e617cb73cd66b51c1141f($fileIdentifier, $file);
|
||||
}
|
||||
|
||||
return $loader;
|
||||
}
|
||||
}
|
||||
|
||||
function composerRequire6278e204890e617cb73cd66b51c1141f($fileIdentifier, $file)
|
||||
{
|
||||
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
|
||||
require $file;
|
||||
|
||||
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
|
||||
}
|
||||
}
|
388
server/vendor/composer/installed.json
vendored
388
server/vendor/composer/installed.json
vendored
|
@ -1,388 +0,0 @@
|
|||
[
|
||||
{
|
||||
"name": "psr/http-message",
|
||||
"version": "1.0",
|
||||
"version_normalized": "1.0.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-fig/http-message.git",
|
||||
"reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-fig/http-message/zipball/85d63699f0dbedb190bbd4b0d2b9dc707ea4c298",
|
||||
"reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3.0"
|
||||
},
|
||||
"time": "2015-05-04 20:22:00",
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0.x-dev"
|
||||
}
|
||||
},
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Psr\\Http\\Message\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "PHP-FIG",
|
||||
"homepage": "http://www.php-fig.org/"
|
||||
}
|
||||
],
|
||||
"description": "Common interface for HTTP messages",
|
||||
"keywords": [
|
||||
"http",
|
||||
"http-message",
|
||||
"psr",
|
||||
"psr-7",
|
||||
"request",
|
||||
"response"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"version": "6.1.1",
|
||||
"version_normalized": "6.1.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/guzzle.git",
|
||||
"reference": "c6851d6e48f63b69357cbfa55bca116448140e0c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/c6851d6e48f63b69357cbfa55bca116448140e0c",
|
||||
"reference": "c6851d6e48f63b69357cbfa55bca116448140e0c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"guzzlehttp/promises": "~1.0",
|
||||
"guzzlehttp/psr7": "~1.1",
|
||||
"php": ">=5.5.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-curl": "*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"time": "2015-11-23 00:47:50",
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "6.1-dev"
|
||||
}
|
||||
},
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "Guzzle is a PHP HTTP client library",
|
||||
"homepage": "http://guzzlephp.org/",
|
||||
"keywords": [
|
||||
"client",
|
||||
"curl",
|
||||
"framework",
|
||||
"http",
|
||||
"http client",
|
||||
"rest",
|
||||
"web service"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "justinrainbow/json-schema",
|
||||
"version": "1.6.1",
|
||||
"version_normalized": "1.6.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/justinrainbow/json-schema.git",
|
||||
"reference": "cc84765fb7317f6b07bd8ac78364747f95b86341"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/cc84765fb7317f6b07bd8ac78364747f95b86341",
|
||||
"reference": "cc84765fb7317f6b07bd8ac78364747f95b86341",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3.29"
|
||||
},
|
||||
"require-dev": {
|
||||
"json-schema/json-schema-test-suite": "1.1.0",
|
||||
"phpdocumentor/phpdocumentor": "~2",
|
||||
"phpunit/phpunit": "~3.7"
|
||||
},
|
||||
"time": "2016-01-25 15:43:01",
|
||||
"bin": [
|
||||
"bin/validate-json"
|
||||
],
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.6.x-dev"
|
||||
}
|
||||
},
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"JsonSchema\\": "src/JsonSchema/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"BSD-3-Clause"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Bruno Prieto Reis",
|
||||
"email": "bruno.p.reis@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Justin Rainbow",
|
||||
"email": "justin.rainbow@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Igor Wiedler",
|
||||
"email": "igor@wiedler.ch"
|
||||
},
|
||||
{
|
||||
"name": "Robert Schönthal",
|
||||
"email": "seroscho@googlemail.com"
|
||||
}
|
||||
],
|
||||
"description": "A library to validate a json schema.",
|
||||
"homepage": "https://github.com/justinrainbow/json-schema",
|
||||
"keywords": [
|
||||
"json",
|
||||
"schema"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "php-opencloud/common",
|
||||
"version": "dev-master",
|
||||
"version_normalized": "9999999-dev",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-opencloud/common.git",
|
||||
"reference": "fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-opencloud/common/zipball/fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62",
|
||||
"reference": "fd027b817c3dd8f83b0c8d9fb1df34ebf25f8c62",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"guzzlehttp/guzzle": "~6.1",
|
||||
"justinrainbow/json-schema": "~1.3",
|
||||
"php": "~7.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"fabpot/php-cs-fixer": "~1.0",
|
||||
"jakub-onderka/php-parallel-lint": "0.*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0",
|
||||
"sami/sami": "dev-master",
|
||||
"satooshi/php-coveralls": "~1.0"
|
||||
},
|
||||
"time": "2016-03-08 12:56:34",
|
||||
"type": "library",
|
||||
"installation-source": "source",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"OpenCloud\\": "src/",
|
||||
"OpenCloud\\Test\\": "tests/unit/",
|
||||
"OpenCloud\\Integration\\": "tests/integration/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Jamie Hannaford",
|
||||
"email": "jamie.hannaford@rackspace.com",
|
||||
"homepage": "https://github.com/jamiehannaford"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/promises",
|
||||
"version": "1.1.0",
|
||||
"version_normalized": "1.1.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/promises.git",
|
||||
"reference": "bb9024c526b22f3fe6ae55a561fd70653d470aa8"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/promises/zipball/bb9024c526b22f3fe6ae55a561fd70653d470aa8",
|
||||
"reference": "bb9024c526b22f3fe6ae55a561fd70653d470aa8",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.5.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~4.0"
|
||||
},
|
||||
"time": "2016-03-08 01:15:46",
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0-dev"
|
||||
}
|
||||
},
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "Guzzle promises library",
|
||||
"keywords": [
|
||||
"promise"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/psr7",
|
||||
"version": "1.2.3",
|
||||
"version_normalized": "1.2.3.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/psr7.git",
|
||||
"reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/psr7/zipball/2e89629ff057ebb49492ba08e6995d3a6a80021b",
|
||||
"reference": "2e89629ff057ebb49492ba08e6995d3a6a80021b",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.4.0",
|
||||
"psr/http-message": "~1.0"
|
||||
},
|
||||
"provide": {
|
||||
"psr/http-message-implementation": "1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~4.0"
|
||||
},
|
||||
"time": "2016-02-18 21:54:00",
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.0-dev"
|
||||
}
|
||||
},
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Psr7\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions_include.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"description": "PSR-7 message implementation",
|
||||
"keywords": [
|
||||
"http",
|
||||
"message",
|
||||
"stream",
|
||||
"uri"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "php-opencloud/openstack",
|
||||
"version": "dev-master",
|
||||
"version_normalized": "9999999-dev",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-opencloud/openstack.git",
|
||||
"reference": "f2ee77024843659d970817a9e7055bb40a3724f9"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-opencloud/openstack/zipball/f2ee77024843659d970817a9e7055bb40a3724f9",
|
||||
"reference": "f2ee77024843659d970817a9e7055bb40a3724f9",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php-opencloud/common": "dev-master"
|
||||
},
|
||||
"require-dev": {
|
||||
"fabpot/php-cs-fixer": "~1.0",
|
||||
"jakub-onderka/php-parallel-lint": "0.*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0",
|
||||
"sami/sami": "dev-master",
|
||||
"satooshi/php-coveralls": "~1.0"
|
||||
},
|
||||
"time": "2016-03-08 14:37:14",
|
||||
"type": "library",
|
||||
"installation-source": "source",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"OpenStack\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Jamie Hannaford",
|
||||
"email": "jamie.hannaford@rackspace.com",
|
||||
"homepage": "https://github.com/jamiehannaford"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
40
server/vendor/guzzlehttp/guzzle/.travis.yml
vendored
40
server/vendor/guzzlehttp/guzzle/.travis.yml
vendored
|
@ -1,40 +0,0 @@
|
|||
language: php
|
||||
|
||||
sudo: false
|
||||
|
||||
php:
|
||||
- 5.5
|
||||
- 5.6
|
||||
- 7.0
|
||||
- hhvm
|
||||
|
||||
before_script:
|
||||
- curl --version
|
||||
- composer self-update
|
||||
- composer install --no-interaction --prefer-source --dev
|
||||
- ~/.nvm/nvm.sh install v0.6.14
|
||||
- ~/.nvm/nvm.sh run v0.6.14
|
||||
|
||||
script: make test
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- php: hhvm
|
||||
- php: 7.0
|
||||
fast_finish: true
|
||||
|
||||
before_deploy:
|
||||
- make package
|
||||
|
||||
deploy:
|
||||
provider: releases
|
||||
api_key:
|
||||
secure: UpypqlYgsU68QT/x40YzhHXvzWjFwCNo9d+G8KAdm7U9+blFfcWhV1aMdzugvPMl6woXgvJj7qHq5tAL4v6oswCORhpSBfLgOQVFaica5LiHsvWlAedOhxGmnJqMTwuepjBCxXhs3+I8Kof1n4oUL9gKytXjOVCX/f7XU1HiinU=
|
||||
file:
|
||||
- build/artifacts/guzzle.phar
|
||||
- build/artifacts/guzzle.zip
|
||||
on:
|
||||
repo: guzzle/guzzle
|
||||
tags: true
|
||||
all_branches: true
|
||||
php: 5.5
|
1203
server/vendor/guzzlehttp/guzzle/CHANGELOG.md
vendored
1203
server/vendor/guzzlehttp/guzzle/CHANGELOG.md
vendored
File diff suppressed because it is too large
Load diff
19
server/vendor/guzzlehttp/guzzle/LICENSE
vendored
19
server/vendor/guzzlehttp/guzzle/LICENSE
vendored
|
@ -1,19 +0,0 @@
|
|||
Copyright (c) 2011-2015 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
|
||||
|
||||
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.
|
90
server/vendor/guzzlehttp/guzzle/README.md
vendored
90
server/vendor/guzzlehttp/guzzle/README.md
vendored
|
@ -1,90 +0,0 @@
|
|||
Guzzle, PHP HTTP client
|
||||
=======================
|
||||
|
||||
[](http://travis-ci.org/guzzle/guzzle)
|
||||
|
||||
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
|
||||
trivial to integrate with web services.
|
||||
|
||||
- Simple interface for building query strings, POST requests, streaming large
|
||||
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
|
||||
etc...
|
||||
- Can send both synchronous and asynchronous requests using the same interface.
|
||||
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
|
||||
to utilize other PSR-7 compatible libraries with Guzzle.
|
||||
- Abstracts away the underlying HTTP transport, allowing you to write
|
||||
environment and transport agnostic code; i.e., no hard dependency on cURL,
|
||||
PHP streams, sockets, or non-blocking event loops.
|
||||
- Middleware system allows you to augment and compose client behavior.
|
||||
|
||||
```php
|
||||
$client = new GuzzleHttp\Client();
|
||||
$res = $client->request('GET', 'https://api.github.com/user', [
|
||||
'auth' => ['user', 'pass']
|
||||
]);
|
||||
echo $res->getStatusCode();
|
||||
// 200
|
||||
echo $res->getHeader('content-type');
|
||||
// 'application/json; charset=utf8'
|
||||
echo $res->getBody();
|
||||
// {"type":"User"...'
|
||||
|
||||
// Send an asynchronous request.
|
||||
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
|
||||
$promise = $client->sendAsync($request)->then(function ($response) {
|
||||
echo 'I completed! ' . $response->getBody();
|
||||
});
|
||||
$promise->wait();
|
||||
```
|
||||
|
||||
## Help and docs
|
||||
|
||||
- [Documentation](http://guzzlephp.org/)
|
||||
- [stackoverflow](http://stackoverflow.com/questions/tagged/guzzle)
|
||||
- [Gitter](https://gitter.im/guzzle/guzzle)
|
||||
|
||||
|
||||
## Installing Guzzle
|
||||
|
||||
The recommended way to install Guzzle is through
|
||||
[Composer](http://getcomposer.org).
|
||||
|
||||
```bash
|
||||
# Install Composer
|
||||
curl -sS https://getcomposer.org/installer | php
|
||||
```
|
||||
|
||||
Next, run the Composer command to install the latest stable version of Guzzle:
|
||||
|
||||
```bash
|
||||
composer.phar require guzzlehttp/guzzle
|
||||
```
|
||||
|
||||
After installing, you need to require Composer's autoloader:
|
||||
|
||||
```php
|
||||
require 'vendor/autoload.php';
|
||||
```
|
||||
|
||||
You can then later update Guzzle using composer:
|
||||
|
||||
```bash
|
||||
composer.phar update
|
||||
```
|
||||
|
||||
|
||||
## Version Guidance
|
||||
|
||||
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 |
|
||||
|---------|-------------|---------------------|--------------|---------------------|---------------------|-------|
|
||||
| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No |
|
||||
| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | N/A | N/A | No |
|
||||
| 5.x | Maintained | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No |
|
||||
| 6.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes |
|
||||
|
||||
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
|
||||
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
|
||||
[guzzle-6-repo]: https://github.com/guzzle/guzzle
|
||||
[guzzle-3-docs]: http://guzzle3.readthedocs.org/en/latest/
|
||||
[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/
|
||||
[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/
|
1203
server/vendor/guzzlehttp/guzzle/UPGRADING.md
vendored
1203
server/vendor/guzzlehttp/guzzle/UPGRADING.md
vendored
File diff suppressed because it is too large
Load diff
41
server/vendor/guzzlehttp/guzzle/composer.json
vendored
41
server/vendor/guzzlehttp/guzzle/composer.json
vendored
|
@ -1,41 +0,0 @@
|
|||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"type": "library",
|
||||
"description": "Guzzle is a PHP HTTP client library",
|
||||
"keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
|
||||
"homepage": "http://guzzlephp.org/",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=5.5.0",
|
||||
"guzzlehttp/psr7": "~1.1",
|
||||
"guzzlehttp/promises": "~1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-curl": "*",
|
||||
"phpunit/phpunit": "~4.0",
|
||||
"psr/log": "~1.0"
|
||||
},
|
||||
"autoload": {
|
||||
"files": ["src/functions_include.php"],
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "6.1-dev"
|
||||
}
|
||||
}
|
||||
}
|
397
server/vendor/guzzlehttp/guzzle/src/Client.php
vendored
397
server/vendor/guzzlehttp/guzzle/src/Client.php
vendored
|
@ -1,397 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJar;
|
||||
use GuzzleHttp\Promise;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* @method ResponseInterface get($uri, array $options = [])
|
||||
* @method ResponseInterface head($uri, array $options = [])
|
||||
* @method ResponseInterface put($uri, array $options = [])
|
||||
* @method ResponseInterface post($uri, array $options = [])
|
||||
* @method ResponseInterface patch($uri, array $options = [])
|
||||
* @method ResponseInterface delete($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface getAsync($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface headAsync($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface putAsync($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface postAsync($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface patchAsync($uri, array $options = [])
|
||||
* @method Promise\PromiseInterface deleteAsync($uri, array $options = [])
|
||||
*/
|
||||
class Client implements ClientInterface
|
||||
{
|
||||
/** @var array Default request options */
|
||||
private $config;
|
||||
|
||||
/**
|
||||
* Clients accept an array of constructor parameters.
|
||||
*
|
||||
* Here's an example of creating a client using a base_uri and an array of
|
||||
* default request options to apply to each request:
|
||||
*
|
||||
* $client = new Client([
|
||||
* 'base_uri' => 'http://www.foo.com/1.0/',
|
||||
* 'timeout' => 0,
|
||||
* 'allow_redirects' => false,
|
||||
* 'proxy' => '192.168.16.1:10'
|
||||
* ]);
|
||||
*
|
||||
* Client configuration settings include the following options:
|
||||
*
|
||||
* - handler: (callable) Function that transfers HTTP requests over the
|
||||
* wire. The function is called with a Psr7\Http\Message\RequestInterface
|
||||
* and array of transfer options, and must return a
|
||||
* GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
|
||||
* Psr7\Http\Message\ResponseInterface on success. "handler" is a
|
||||
* constructor only option that cannot be overridden in per/request
|
||||
* options. If no handler is provided, a default handler will be created
|
||||
* that enables all of the request options below by attaching all of the
|
||||
* default middleware to the handler.
|
||||
* - base_uri: (string|UriInterface) Base URI of the client that is merged
|
||||
* into relative URIs. Can be a string or instance of UriInterface.
|
||||
* - **: any request option
|
||||
*
|
||||
* @param array $config Client configuration settings.
|
||||
*
|
||||
* @see \GuzzleHttp\RequestOptions for a list of available request options.
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
if (!isset($config['handler'])) {
|
||||
$config['handler'] = HandlerStack::create();
|
||||
}
|
||||
|
||||
// Convert the base_uri to a UriInterface
|
||||
if (isset($config['base_uri'])) {
|
||||
$config['base_uri'] = Psr7\uri_for($config['base_uri']);
|
||||
}
|
||||
|
||||
$this->configureDefaults($config);
|
||||
}
|
||||
|
||||
public function __call($method, $args)
|
||||
{
|
||||
if (count($args) < 1) {
|
||||
throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
|
||||
}
|
||||
|
||||
$uri = $args[0];
|
||||
$opts = isset($args[1]) ? $args[1] : [];
|
||||
|
||||
return substr($method, -5) === 'Async'
|
||||
? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
|
||||
: $this->request($method, $uri, $opts);
|
||||
}
|
||||
|
||||
public function sendAsync(RequestInterface $request, array $options = [])
|
||||
{
|
||||
// Merge the base URI into the request URI if needed.
|
||||
$options = $this->prepareDefaults($options);
|
||||
|
||||
return $this->transfer(
|
||||
$request->withUri($this->buildUri($request->getUri(), $options)),
|
||||
$options
|
||||
);
|
||||
}
|
||||
|
||||
public function send(RequestInterface $request, array $options = [])
|
||||
{
|
||||
$options[RequestOptions::SYNCHRONOUS] = true;
|
||||
return $this->sendAsync($request, $options)->wait();
|
||||
}
|
||||
|
||||
public function requestAsync($method, $uri = null, array $options = [])
|
||||
{
|
||||
$options = $this->prepareDefaults($options);
|
||||
// Remove request modifying parameter because it can be done up-front.
|
||||
$headers = isset($options['headers']) ? $options['headers'] : [];
|
||||
$body = isset($options['body']) ? $options['body'] : null;
|
||||
$version = isset($options['version']) ? $options['version'] : '1.1';
|
||||
// Merge the URI into the base URI.
|
||||
$uri = $this->buildUri($uri, $options);
|
||||
if (is_array($body)) {
|
||||
$this->invalidBody();
|
||||
}
|
||||
$request = new Psr7\Request($method, $uri, $headers, $body, $version);
|
||||
// Remove the option so that they are not doubly-applied.
|
||||
unset($options['headers'], $options['body'], $options['version']);
|
||||
|
||||
return $this->transfer($request, $options);
|
||||
}
|
||||
|
||||
public function request($method, $uri = null, array $options = [])
|
||||
{
|
||||
$options[RequestOptions::SYNCHRONOUS] = true;
|
||||
return $this->requestAsync($method, $uri, $options)->wait();
|
||||
}
|
||||
|
||||
public function getConfig($option = null)
|
||||
{
|
||||
return $option === null
|
||||
? $this->config
|
||||
: (isset($this->config[$option]) ? $this->config[$option] : null);
|
||||
}
|
||||
|
||||
private function buildUri($uri, array $config)
|
||||
{
|
||||
if (!isset($config['base_uri'])) {
|
||||
return $uri instanceof UriInterface ? $uri : new Psr7\Uri($uri);
|
||||
}
|
||||
|
||||
return Psr7\Uri::resolve(Psr7\uri_for($config['base_uri']), $uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the default options for a client.
|
||||
*
|
||||
* @param array $config
|
||||
*/
|
||||
private function configureDefaults(array $config)
|
||||
{
|
||||
$defaults = [
|
||||
'allow_redirects' => RedirectMiddleware::$defaultSettings,
|
||||
'http_errors' => true,
|
||||
'decode_content' => true,
|
||||
'verify' => true,
|
||||
'cookies' => false
|
||||
];
|
||||
|
||||
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set
|
||||
if ($proxy = getenv('HTTP_PROXY')) {
|
||||
$defaults['proxy']['http'] = $proxy;
|
||||
}
|
||||
|
||||
if ($proxy = getenv('HTTPS_PROXY')) {
|
||||
$defaults['proxy']['https'] = $proxy;
|
||||
}
|
||||
|
||||
if ($noProxy = getenv('NO_PROXY')) {
|
||||
$cleanedNoProxy = str_replace(' ', '', $noProxy);
|
||||
$defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
|
||||
}
|
||||
|
||||
$this->config = $config + $defaults;
|
||||
|
||||
if (!empty($config['cookies']) && $config['cookies'] === true) {
|
||||
$this->config['cookies'] = new CookieJar();
|
||||
}
|
||||
|
||||
// Add the default user-agent header.
|
||||
if (!isset($this->config['headers'])) {
|
||||
$this->config['headers'] = ['User-Agent' => default_user_agent()];
|
||||
} else {
|
||||
// Add the User-Agent header if one was not already set.
|
||||
foreach (array_keys($this->config['headers']) as $name) {
|
||||
if (strtolower($name) === 'user-agent') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
$this->config['headers']['User-Agent'] = default_user_agent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges default options into the array.
|
||||
*
|
||||
* @param array $options Options to modify by reference
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function prepareDefaults($options)
|
||||
{
|
||||
$defaults = $this->config;
|
||||
|
||||
if (!empty($defaults['headers'])) {
|
||||
// Default headers are only added if they are not present.
|
||||
$defaults['_conditional'] = $defaults['headers'];
|
||||
unset($defaults['headers']);
|
||||
}
|
||||
|
||||
// Special handling for headers is required as they are added as
|
||||
// conditional headers and as headers passed to a request ctor.
|
||||
if (array_key_exists('headers', $options)) {
|
||||
// Allows default headers to be unset.
|
||||
if ($options['headers'] === null) {
|
||||
$defaults['_conditional'] = null;
|
||||
unset($options['headers']);
|
||||
} elseif (!is_array($options['headers'])) {
|
||||
throw new \InvalidArgumentException('headers must be an array');
|
||||
}
|
||||
}
|
||||
|
||||
// Shallow merge defaults underneath options.
|
||||
$result = $options + $defaults;
|
||||
|
||||
// Remove null values.
|
||||
foreach ($result as $k => $v) {
|
||||
if ($v === null) {
|
||||
unset($result[$k]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfers the given request and applies request options.
|
||||
*
|
||||
* The URI of the request is not modified and the request options are used
|
||||
* as-is without merging in default options.
|
||||
*
|
||||
* @param RequestInterface $request
|
||||
* @param array $options
|
||||
*
|
||||
* @return Promise\PromiseInterface
|
||||
*/
|
||||
private function transfer(RequestInterface $request, array $options)
|
||||
{
|
||||
// save_to -> sink
|
||||
if (isset($options['save_to'])) {
|
||||
$options['sink'] = $options['save_to'];
|
||||
unset($options['save_to']);
|
||||
}
|
||||
|
||||
// exceptions -> http_error
|
||||
if (isset($options['exceptions'])) {
|
||||
$options['http_errors'] = $options['exceptions'];
|
||||
unset($options['exceptions']);
|
||||
}
|
||||
|
||||
$request = $this->applyOptions($request, $options);
|
||||
$handler = $options['handler'];
|
||||
|
||||
try {
|
||||
return Promise\promise_for($handler($request, $options));
|
||||
} catch (\Exception $e) {
|
||||
return Promise\rejection_for($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the array of request options to a request.
|
||||
*
|
||||
* @param RequestInterface $request
|
||||
* @param array $options
|
||||
*
|
||||
* @return RequestInterface
|
||||
*/
|
||||
private function applyOptions(RequestInterface $request, array &$options)
|
||||
{
|
||||
$modify = [];
|
||||
|
||||
if (isset($options['form_params'])) {
|
||||
if (isset($options['multipart'])) {
|
||||
throw new \InvalidArgumentException('You cannot use '
|
||||
. 'form_params and multipart at the same time. Use the '
|
||||
. 'form_params option if you want to send application/'
|
||||
. 'x-www-form-urlencoded requests, and the multipart '
|
||||
. 'option to send multipart/form-data requests.');
|
||||
}
|
||||
$options['body'] = http_build_query($options['form_params'], null, '&');
|
||||
unset($options['form_params']);
|
||||
$options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
}
|
||||
|
||||
if (isset($options['multipart'])) {
|
||||
$elements = $options['multipart'];
|
||||
unset($options['multipart']);
|
||||
$options['body'] = new Psr7\MultipartStream($elements);
|
||||
}
|
||||
|
||||
if (!empty($options['decode_content'])
|
||||
&& $options['decode_content'] !== true
|
||||
) {
|
||||
$modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
|
||||
}
|
||||
|
||||
if (isset($options['headers'])) {
|
||||
if (isset($modify['set_headers'])) {
|
||||
$modify['set_headers'] = $options['headers'] + $modify['set_headers'];
|
||||
} else {
|
||||
$modify['set_headers'] = $options['headers'];
|
||||
}
|
||||
unset($options['headers']);
|
||||
}
|
||||
|
||||
if (isset($options['body'])) {
|
||||
if (is_array($options['body'])) {
|
||||
$this->invalidBody();
|
||||
}
|
||||
$modify['body'] = Psr7\stream_for($options['body']);
|
||||
unset($options['body']);
|
||||
}
|
||||
|
||||
if (!empty($options['auth'])) {
|
||||
$value = $options['auth'];
|
||||
$type = is_array($value)
|
||||
? (isset($value[2]) ? strtolower($value[2]) : 'basic')
|
||||
: $value;
|
||||
$config['auth'] = $value;
|
||||
switch (strtolower($type)) {
|
||||
case 'basic':
|
||||
$modify['set_headers']['Authorization'] = 'Basic '
|
||||
. base64_encode("$value[0]:$value[1]");
|
||||
break;
|
||||
case 'digest':
|
||||
// @todo: Do not rely on curl
|
||||
$options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
|
||||
$options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['query'])) {
|
||||
$value = $options['query'];
|
||||
if (is_array($value)) {
|
||||
$value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
if (!is_string($value)) {
|
||||
throw new \InvalidArgumentException('query must be a string or array');
|
||||
}
|
||||
$modify['query'] = $value;
|
||||
unset($options['query']);
|
||||
}
|
||||
|
||||
if (isset($options['json'])) {
|
||||
$modify['body'] = Psr7\stream_for(json_encode($options['json']));
|
||||
$options['_conditional']['Content-Type'] = 'application/json';
|
||||
unset($options['json']);
|
||||
}
|
||||
|
||||
$request = Psr7\modify_request($request, $modify);
|
||||
if ($request->getBody() instanceof Psr7\MultipartStream) {
|
||||
// Use a multipart/form-data POST if a Content-Type is not set.
|
||||
$options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
|
||||
. $request->getBody()->getBoundary();
|
||||
}
|
||||
|
||||
// Merge in conditional headers if they are not present.
|
||||
if (isset($options['_conditional'])) {
|
||||
// Build up the changes so it's in a single clone of the message.
|
||||
$modify = [];
|
||||
foreach ($options['_conditional'] as $k => $v) {
|
||||
if (!$request->hasHeader($k)) {
|
||||
$modify['set_headers'][$k] = $v;
|
||||
}
|
||||
}
|
||||
$request = Psr7\modify_request($request, $modify);
|
||||
// Don't pass this internal value along to middleware/handlers.
|
||||
unset($options['_conditional']);
|
||||
}
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
private function invalidBody()
|
||||
{
|
||||
throw new \InvalidArgumentException('Passing in the "body" request '
|
||||
. 'option as an array to send a POST request has been deprecated. '
|
||||
. 'Please use the "form_params" request option to send a '
|
||||
. 'application/x-www-form-urlencoded request, or a the "multipart" '
|
||||
. 'request option to send a multipart/form-data request.');
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Client interface for sending HTTP requests.
|
||||
*/
|
||||
interface ClientInterface
|
||||
{
|
||||
const VERSION = '6.1.1';
|
||||
|
||||
/**
|
||||
* Send an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send
|
||||
* @param array $options Request options to apply to the given
|
||||
* request and to the transfer.
|
||||
*
|
||||
* @return ResponseInterface
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function send(RequestInterface $request, array $options = []);
|
||||
|
||||
/**
|
||||
* Asynchronously send an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send
|
||||
* @param array $options Request options to apply to the given
|
||||
* request and to the transfer.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public function sendAsync(RequestInterface $request, array $options = []);
|
||||
|
||||
/**
|
||||
* Create and send an HTTP request.
|
||||
*
|
||||
* Use an absolute path to override the base path of the client, or a
|
||||
* relative path to append to the base path of the client. The URL can
|
||||
* contain the query string as well.
|
||||
*
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI object or string.
|
||||
* @param array $options Request options to apply.
|
||||
*
|
||||
* @return ResponseInterface
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function request($method, $uri, array $options = []);
|
||||
|
||||
/**
|
||||
* Create and send an asynchronous HTTP request.
|
||||
*
|
||||
* Use an absolute path to override the base path of the client, or a
|
||||
* relative path to append to the base path of the client. The URL can
|
||||
* contain the query string as well. Use an array to provide a URL
|
||||
* template and additional variables to use in the URL template expansion.
|
||||
*
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI object or string.
|
||||
* @param array $options Request options to apply.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public function requestAsync($method, $uri, array $options = []);
|
||||
|
||||
/**
|
||||
* Get a client configuration option.
|
||||
*
|
||||
* These options include default request options of the client, a "handler"
|
||||
* (if utilized by the concrete client), and a "base_uri" if utilized by
|
||||
* the concrete client.
|
||||
*
|
||||
* @param string|null $option The config option to retrieve.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getConfig($option = null);
|
||||
}
|
|
@ -1,277 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Cookie jar that stores cookies an an array
|
||||
*/
|
||||
class CookieJar implements CookieJarInterface
|
||||
{
|
||||
/** @var SetCookie[] Loaded cookie data */
|
||||
private $cookies = [];
|
||||
|
||||
/** @var bool */
|
||||
private $strictMode;
|
||||
|
||||
/**
|
||||
* @param bool $strictMode Set to true to throw exceptions when invalid
|
||||
* cookies are added to the cookie jar.
|
||||
* @param array $cookieArray Array of SetCookie objects or a hash of
|
||||
* arrays that can be used with the SetCookie
|
||||
* constructor
|
||||
*/
|
||||
public function __construct($strictMode = false, $cookieArray = [])
|
||||
{
|
||||
$this->strictMode = $strictMode;
|
||||
|
||||
foreach ($cookieArray as $cookie) {
|
||||
if (!($cookie instanceof SetCookie)) {
|
||||
$cookie = new SetCookie($cookie);
|
||||
}
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Cookie jar from an associative array and domain.
|
||||
*
|
||||
* @param array $cookies Cookies to create the jar from
|
||||
* @param string $domain Domain to set the cookies to
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $cookies, $domain)
|
||||
{
|
||||
$cookieJar = new self();
|
||||
foreach ($cookies as $name => $value) {
|
||||
$cookieJar->setCookie(new SetCookie([
|
||||
'Domain' => $domain,
|
||||
'Name' => $name,
|
||||
'Value' => $value,
|
||||
'Discard' => true
|
||||
]));
|
||||
}
|
||||
|
||||
return $cookieJar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote the cookie value if it is not already quoted and it contains
|
||||
* problematic characters.
|
||||
*
|
||||
* @param string $value Value that may or may not need to be quoted
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getCookieValue($value)
|
||||
{
|
||||
if (substr($value, 0, 1) !== '"' &&
|
||||
substr($value, -1, 1) !== '"' &&
|
||||
strpbrk($value, ';,=')
|
||||
) {
|
||||
$value = '"' . $value . '"';
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate if this cookie should be persisted to storage
|
||||
* that survives between requests.
|
||||
*
|
||||
* @param SetCookie $cookie Being evaluated.
|
||||
* @param bool $allowSessionCookies If we should persist session cookies
|
||||
* @return bool
|
||||
*/
|
||||
public static function shouldPersist(
|
||||
SetCookie $cookie,
|
||||
$allowSessionCookies = false
|
||||
) {
|
||||
if ($cookie->getExpires() || $allowSessionCookies) {
|
||||
if (!$cookie->getDiscard()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return array_map(function (SetCookie $cookie) {
|
||||
return $cookie->toArray();
|
||||
}, $this->getIterator()->getArrayCopy());
|
||||
}
|
||||
|
||||
public function clear($domain = null, $path = null, $name = null)
|
||||
{
|
||||
if (!$domain) {
|
||||
$this->cookies = [];
|
||||
return;
|
||||
} elseif (!$path) {
|
||||
$this->cookies = array_filter(
|
||||
$this->cookies,
|
||||
function (SetCookie $cookie) use ($path, $domain) {
|
||||
return !$cookie->matchesDomain($domain);
|
||||
}
|
||||
);
|
||||
} elseif (!$name) {
|
||||
$this->cookies = array_filter(
|
||||
$this->cookies,
|
||||
function (SetCookie $cookie) use ($path, $domain) {
|
||||
return !($cookie->matchesPath($path) &&
|
||||
$cookie->matchesDomain($domain));
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$this->cookies = array_filter(
|
||||
$this->cookies,
|
||||
function (SetCookie $cookie) use ($path, $domain, $name) {
|
||||
return !($cookie->getName() == $name &&
|
||||
$cookie->matchesPath($path) &&
|
||||
$cookie->matchesDomain($domain));
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function clearSessionCookies()
|
||||
{
|
||||
$this->cookies = array_filter(
|
||||
$this->cookies,
|
||||
function (SetCookie $cookie) {
|
||||
return !$cookie->getDiscard() && $cookie->getExpires();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public function setCookie(SetCookie $cookie)
|
||||
{
|
||||
// If the name string is empty (but not 0), ignore the set-cookie
|
||||
// string entirely.
|
||||
$name = $cookie->getName();
|
||||
if (!$name && $name !== '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only allow cookies with set and valid domain, name, value
|
||||
$result = $cookie->validate();
|
||||
if ($result !== true) {
|
||||
if ($this->strictMode) {
|
||||
throw new \RuntimeException('Invalid cookie: ' . $result);
|
||||
} else {
|
||||
$this->removeCookieIfEmpty($cookie);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve conflicts with previously set cookies
|
||||
foreach ($this->cookies as $i => $c) {
|
||||
|
||||
// Two cookies are identical, when their path, and domain are
|
||||
// identical.
|
||||
if ($c->getPath() != $cookie->getPath() ||
|
||||
$c->getDomain() != $cookie->getDomain() ||
|
||||
$c->getName() != $cookie->getName()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The previously set cookie is a discard cookie and this one is
|
||||
// not so allow the new cookie to be set
|
||||
if (!$cookie->getDiscard() && $c->getDiscard()) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the new cookie's expiration is further into the future, then
|
||||
// replace the old cookie
|
||||
if ($cookie->getExpires() > $c->getExpires()) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the value has changed, we better change it
|
||||
if ($cookie->getValue() !== $c->getValue()) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// The cookie exists, so no need to continue
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->cookies[] = $cookie;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function count()
|
||||
{
|
||||
return count($this->cookies);
|
||||
}
|
||||
|
||||
public function getIterator()
|
||||
{
|
||||
return new \ArrayIterator(array_values($this->cookies));
|
||||
}
|
||||
|
||||
public function extractCookies(
|
||||
RequestInterface $request,
|
||||
ResponseInterface $response
|
||||
) {
|
||||
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
|
||||
foreach ($cookieHeader as $cookie) {
|
||||
$sc = SetCookie::fromString($cookie);
|
||||
if (!$sc->getDomain()) {
|
||||
$sc->setDomain($request->getUri()->getHost());
|
||||
}
|
||||
$this->setCookie($sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function withCookieHeader(RequestInterface $request)
|
||||
{
|
||||
$values = [];
|
||||
$uri = $request->getUri();
|
||||
$scheme = $uri->getScheme();
|
||||
$host = $uri->getHost();
|
||||
$path = $uri->getPath() ?: '/';
|
||||
|
||||
foreach ($this->cookies as $cookie) {
|
||||
if ($cookie->matchesPath($path) &&
|
||||
$cookie->matchesDomain($host) &&
|
||||
!$cookie->isExpired() &&
|
||||
(!$cookie->getSecure() || $scheme == 'https')
|
||||
) {
|
||||
$values[] = $cookie->getName() . '='
|
||||
. self::getCookieValue($cookie->getValue());
|
||||
}
|
||||
}
|
||||
|
||||
return $values
|
||||
? $request->withHeader('Cookie', implode('; ', $values))
|
||||
: $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a cookie already exists and the server asks to set it again with a
|
||||
* null value, the cookie must be deleted.
|
||||
*
|
||||
* @param SetCookie $cookie
|
||||
*/
|
||||
private function removeCookieIfEmpty(SetCookie $cookie)
|
||||
{
|
||||
$cookieValue = $cookie->getValue();
|
||||
if ($cookieValue === null || $cookieValue === '') {
|
||||
$this->clear(
|
||||
$cookie->getDomain(),
|
||||
$cookie->getPath(),
|
||||
$cookie->getName()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Stores HTTP cookies.
|
||||
*
|
||||
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
|
||||
* CookieJarInterface instances automatically expire contained cookies when
|
||||
* necessary. Subclasses are also responsible for storing and retrieving
|
||||
* cookies from a file, database, etc.
|
||||
*
|
||||
* @link http://docs.python.org/2/library/cookielib.html Inspiration
|
||||
*/
|
||||
interface CookieJarInterface extends \Countable, \IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Create a request with added cookie headers.
|
||||
*
|
||||
* If no matching cookies are found in the cookie jar, then no Cookie
|
||||
* header is added to the request and the same request is returned.
|
||||
*
|
||||
* @param RequestInterface $request Request object to modify.
|
||||
*
|
||||
* @return RequestInterface returns the modified request.
|
||||
*/
|
||||
public function withCookieHeader(RequestInterface $request);
|
||||
|
||||
/**
|
||||
* Extract cookies from an HTTP response and store them in the CookieJar.
|
||||
*
|
||||
* @param RequestInterface $request Request that was sent
|
||||
* @param ResponseInterface $response Response that was received
|
||||
*/
|
||||
public function extractCookies(
|
||||
RequestInterface $request,
|
||||
ResponseInterface $response
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets a cookie in the cookie jar.
|
||||
*
|
||||
* @param SetCookie $cookie Cookie to set.
|
||||
*
|
||||
* @return bool Returns true on success or false on failure
|
||||
*/
|
||||
public function setCookie(SetCookie $cookie);
|
||||
|
||||
/**
|
||||
* Remove cookies currently held in the cookie jar.
|
||||
*
|
||||
* Invoking this method without arguments will empty the whole cookie jar.
|
||||
* If given a $domain argument only cookies belonging to that domain will
|
||||
* be removed. If given a $domain and $path argument, cookies belonging to
|
||||
* the specified path within that domain are removed. If given all three
|
||||
* arguments, then the cookie with the specified name, path and domain is
|
||||
* removed.
|
||||
*
|
||||
* @param string $domain Clears cookies matching a domain
|
||||
* @param string $path Clears cookies matching a domain and path
|
||||
* @param string $name Clears cookies matching a domain, path, and name
|
||||
*
|
||||
* @return CookieJarInterface
|
||||
*/
|
||||
public function clear($domain = null, $path = null, $name = null);
|
||||
|
||||
/**
|
||||
* Discard all sessions cookies.
|
||||
*
|
||||
* Removes cookies that don't have an expire field or a have a discard
|
||||
* field set to true. To be called when the user agent shuts down according
|
||||
* to RFC 2965.
|
||||
*/
|
||||
public function clearSessionCookies();
|
||||
|
||||
/**
|
||||
* Converts the cookie jar to an array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray();
|
||||
}
|
|
@ -1,87 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
/**
|
||||
* Persists non-session cookies using a JSON formatted file
|
||||
*/
|
||||
class FileCookieJar extends CookieJar
|
||||
{
|
||||
/** @var string filename */
|
||||
private $filename;
|
||||
|
||||
/** @var bool Control whether to persist session cookies or not. */
|
||||
private $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* Create a new FileCookieJar object
|
||||
*
|
||||
* @param string $cookieFile File to store the cookie data
|
||||
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||
* in the cookie jar.
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be found or created
|
||||
*/
|
||||
public function __construct($cookieFile, $storeSessionCookies = false)
|
||||
{
|
||||
$this->filename = $cookieFile;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
|
||||
if (file_exists($cookieFile)) {
|
||||
$this->load($cookieFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the file when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->save($this->filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the cookies to a file.
|
||||
*
|
||||
* @param string $filename File to save
|
||||
* @throws \RuntimeException if the file cannot be found or created
|
||||
*/
|
||||
public function save($filename)
|
||||
{
|
||||
$json = [];
|
||||
foreach ($this as $cookie) {
|
||||
/** @var SetCookie $cookie */
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$json[] = $cookie->toArray();
|
||||
}
|
||||
}
|
||||
|
||||
if (false === file_put_contents($filename, json_encode($json))) {
|
||||
throw new \RuntimeException("Unable to save file {$filename}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cookies from a JSON formatted file.
|
||||
*
|
||||
* Old cookies are kept unless overwritten by newly loaded ones.
|
||||
*
|
||||
* @param string $filename Cookie file to load.
|
||||
* @throws \RuntimeException if the file cannot be loaded.
|
||||
*/
|
||||
public function load($filename)
|
||||
{
|
||||
$json = file_get_contents($filename);
|
||||
if (false === $json) {
|
||||
throw new \RuntimeException("Unable to load file {$filename}");
|
||||
}
|
||||
|
||||
$data = json_decode($json, true);
|
||||
if (is_array($data)) {
|
||||
foreach (json_decode($json, true) as $cookie) {
|
||||
$this->setCookie(new SetCookie($cookie));
|
||||
}
|
||||
} elseif (strlen($data)) {
|
||||
throw new \RuntimeException("Invalid cookie file: {$filename}");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
/**
|
||||
* Persists cookies in the client session
|
||||
*/
|
||||
class SessionCookieJar extends CookieJar
|
||||
{
|
||||
/** @var string session key */
|
||||
private $sessionKey;
|
||||
|
||||
/** @var bool Control whether to persist session cookies or not. */
|
||||
private $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* Create a new SessionCookieJar object
|
||||
*
|
||||
* @param string $sessionKey Session key name to store the cookie
|
||||
* data in session
|
||||
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||
* in the cookie jar.
|
||||
*/
|
||||
public function __construct($sessionKey, $storeSessionCookies = false)
|
||||
{
|
||||
$this->sessionKey = $sessionKey;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
$this->load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves cookies to session when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save cookies to the client session
|
||||
*/
|
||||
public function save()
|
||||
{
|
||||
$json = [];
|
||||
foreach ($this as $cookie) {
|
||||
/** @var SetCookie $cookie */
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$json[] = $cookie->toArray();
|
||||
}
|
||||
}
|
||||
|
||||
$_SESSION[$this->sessionKey] = json_encode($json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the contents of the client session into the data array
|
||||
*/
|
||||
protected function load()
|
||||
{
|
||||
$cookieJar = isset($_SESSION[$this->sessionKey])
|
||||
? $_SESSION[$this->sessionKey]
|
||||
: null;
|
||||
|
||||
$data = json_decode($cookieJar, true);
|
||||
if (is_array($data)) {
|
||||
foreach ($data as $cookie) {
|
||||
$this->setCookie(new SetCookie($cookie));
|
||||
}
|
||||
} elseif (strlen($data)) {
|
||||
throw new \RuntimeException("Invalid cookie data");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,404 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
/**
|
||||
* Set-Cookie object
|
||||
*/
|
||||
class SetCookie
|
||||
{
|
||||
/** @var array */
|
||||
private static $defaults = [
|
||||
'Name' => null,
|
||||
'Value' => null,
|
||||
'Domain' => null,
|
||||
'Path' => '/',
|
||||
'Max-Age' => null,
|
||||
'Expires' => null,
|
||||
'Secure' => false,
|
||||
'Discard' => false,
|
||||
'HttpOnly' => false
|
||||
];
|
||||
|
||||
/** @var array Cookie data */
|
||||
private $data;
|
||||
|
||||
/**
|
||||
* Create a new SetCookie object from a string
|
||||
*
|
||||
* @param string $cookie Set-Cookie header string
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function fromString($cookie)
|
||||
{
|
||||
// Create the default return array
|
||||
$data = self::$defaults;
|
||||
// Explode the cookie string using a series of semicolons
|
||||
$pieces = array_filter(array_map('trim', explode(';', $cookie)));
|
||||
// The name of the cookie (first kvp) must include an equal sign.
|
||||
if (empty($pieces) || !strpos($pieces[0], '=')) {
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
// Add the cookie pieces into the parsed data array
|
||||
foreach ($pieces as $part) {
|
||||
|
||||
$cookieParts = explode('=', $part, 2);
|
||||
$key = trim($cookieParts[0]);
|
||||
$value = isset($cookieParts[1])
|
||||
? trim($cookieParts[1], " \n\r\t\0\x0B")
|
||||
: true;
|
||||
|
||||
// Only check for non-cookies when cookies have been found
|
||||
if (empty($data['Name'])) {
|
||||
$data['Name'] = $key;
|
||||
$data['Value'] = $value;
|
||||
} else {
|
||||
foreach (array_keys(self::$defaults) as $search) {
|
||||
if (!strcasecmp($search, $key)) {
|
||||
$data[$search] = $value;
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
$data[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data Array of cookie data provided by a Cookie parser
|
||||
*/
|
||||
public function __construct(array $data = [])
|
||||
{
|
||||
$this->data = array_replace(self::$defaults, $data);
|
||||
// Extract the Expires value and turn it into a UNIX timestamp if needed
|
||||
if (!$this->getExpires() && $this->getMaxAge()) {
|
||||
// Calculate the Expires date
|
||||
$this->setExpires(time() + $this->getMaxAge());
|
||||
} elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
|
||||
$this->setExpires($this->getExpires());
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
$str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
|
||||
foreach ($this->data as $k => $v) {
|
||||
if ($k != 'Name' && $k != 'Value' && $v !== null && $v !== false) {
|
||||
if ($k == 'Expires') {
|
||||
$str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
|
||||
} else {
|
||||
$str .= ($v === true ? $k : "{$k}={$v}") . '; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rtrim($str, '; ');
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->data['Name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie name
|
||||
*
|
||||
* @param string $name Cookie name
|
||||
*/
|
||||
public function setName($name)
|
||||
{
|
||||
$this->data['Name'] = $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie value
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getValue()
|
||||
{
|
||||
return $this->data['Value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie value
|
||||
*
|
||||
* @param string $value Cookie value
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
$this->data['Value'] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the domain
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDomain()
|
||||
{
|
||||
return $this->data['Domain'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the domain of the cookie
|
||||
*
|
||||
* @param string $domain
|
||||
*/
|
||||
public function setDomain($domain)
|
||||
{
|
||||
$this->data['Domain'] = $domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
return $this->data['Path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the path of the cookie
|
||||
*
|
||||
* @param string $path Path of the cookie
|
||||
*/
|
||||
public function setPath($path)
|
||||
{
|
||||
$this->data['Path'] = $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum lifetime of the cookie in seconds
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMaxAge()
|
||||
{
|
||||
return $this->data['Max-Age'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the max-age of the cookie
|
||||
*
|
||||
* @param int $maxAge Max age of the cookie in seconds
|
||||
*/
|
||||
public function setMaxAge($maxAge)
|
||||
{
|
||||
$this->data['Max-Age'] = $maxAge;
|
||||
}
|
||||
|
||||
/**
|
||||
* The UNIX timestamp when the cookie Expires
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getExpires()
|
||||
{
|
||||
return $this->data['Expires'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the unix timestamp for which the cookie will expire
|
||||
*
|
||||
* @param int $timestamp Unix timestamp
|
||||
*/
|
||||
public function setExpires($timestamp)
|
||||
{
|
||||
$this->data['Expires'] = is_numeric($timestamp)
|
||||
? (int) $timestamp
|
||||
: strtotime($timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a secure cookie
|
||||
*
|
||||
* @return null|bool
|
||||
*/
|
||||
public function getSecure()
|
||||
{
|
||||
return $this->data['Secure'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not the cookie is secure
|
||||
*
|
||||
* @param bool $secure Set to true or false if secure
|
||||
*/
|
||||
public function setSecure($secure)
|
||||
{
|
||||
$this->data['Secure'] = $secure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a session cookie
|
||||
*
|
||||
* @return null|bool
|
||||
*/
|
||||
public function getDiscard()
|
||||
{
|
||||
return $this->data['Discard'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not this is a session cookie
|
||||
*
|
||||
* @param bool $discard Set to true or false if this is a session cookie
|
||||
*/
|
||||
public function setDiscard($discard)
|
||||
{
|
||||
$this->data['Discard'] = $discard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is an HTTP only cookie
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getHttpOnly()
|
||||
{
|
||||
return $this->data['HttpOnly'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not this is an HTTP only cookie
|
||||
*
|
||||
* @param bool $httpOnly Set to true or false if this is HTTP only
|
||||
*/
|
||||
public function setHttpOnly($httpOnly)
|
||||
{
|
||||
$this->data['HttpOnly'] = $httpOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie matches a path value.
|
||||
*
|
||||
* A request-path path-matches a given cookie-path if at least one of
|
||||
* the following conditions holds:
|
||||
*
|
||||
* - The cookie-path and the request-path are identical.
|
||||
* - The cookie-path is a prefix of the request-path, and the last
|
||||
* character of the cookie-path is %x2F ("/").
|
||||
* - The cookie-path is a prefix of the request-path, and the first
|
||||
* character of the request-path that is not included in the cookie-
|
||||
* path is a %x2F ("/") character.
|
||||
*
|
||||
* @param string $requestPath Path to check against
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function matchesPath($requestPath)
|
||||
{
|
||||
$cookiePath = $this->getPath();
|
||||
|
||||
// Match on exact matches or when path is the default empty "/"
|
||||
if ($cookiePath == '/' || $cookiePath == $requestPath) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ensure that the cookie-path is a prefix of the request path.
|
||||
if (0 !== strpos($requestPath, $cookiePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match if the last character of the cookie-path is "/"
|
||||
if (substr($cookiePath, -1, 1) == '/') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Match if the first character not included in cookie path is "/"
|
||||
return substr($requestPath, strlen($cookiePath), 1) == '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie matches a domain value
|
||||
*
|
||||
* @param string $domain Domain to check against
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function matchesDomain($domain)
|
||||
{
|
||||
// Remove the leading '.' as per spec in RFC 6265.
|
||||
// http://tools.ietf.org/html/rfc6265#section-5.2.3
|
||||
$cookieDomain = ltrim($this->getDomain(), '.');
|
||||
|
||||
// Domain not set or exact match.
|
||||
if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Matching the subdomain according to RFC 6265.
|
||||
// http://tools.ietf.org/html/rfc6265#section-5.1.3
|
||||
if (filter_var($domain, FILTER_VALIDATE_IP)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) preg_match('/\.' . preg_quote($cookieDomain) . '$/', $domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie is expired
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isExpired()
|
||||
{
|
||||
return $this->getExpires() && time() > $this->getExpires();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie is valid according to RFC 6265
|
||||
*
|
||||
* @return bool|string Returns true if valid or an error message if invalid
|
||||
*/
|
||||
public function validate()
|
||||
{
|
||||
// Names must not be empty, but can be 0
|
||||
$name = $this->getName();
|
||||
if (empty($name) && !is_numeric($name)) {
|
||||
return 'The cookie name must not be empty';
|
||||
}
|
||||
|
||||
// Check if any of the invalid characters are present in the cookie name
|
||||
if (preg_match(
|
||||
'/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
|
||||
$name)
|
||||
) {
|
||||
return 'Cookie name must not contain invalid characters: ASCII '
|
||||
. 'Control characters (0-31;127), space, tab and the '
|
||||
. 'following characters: ()<>@,;:\"/?={}';
|
||||
}
|
||||
|
||||
// Value must not be empty, but can be 0
|
||||
$value = $this->getValue();
|
||||
if (empty($value) && !is_numeric($value)) {
|
||||
return 'The cookie value must not be empty';
|
||||
}
|
||||
|
||||
// Domains must not be empty, but can be 0
|
||||
// A "0" is not a valid internet domain, but may be used as server name
|
||||
// in a private network.
|
||||
$domain = $this->getDomain();
|
||||
if (empty($domain) && !is_numeric($domain)) {
|
||||
return 'The cookie domain must not be empty';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception when an HTTP error occurs (4xx or 5xx error)
|
||||
*/
|
||||
class BadResponseException extends RequestException {}
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception when a client error is encountered (4xx codes)
|
||||
*/
|
||||
class ClientException extends BadResponseException {}
|
|
@ -1,37 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Exception thrown when a connection cannot be established.
|
||||
*
|
||||
* Note that no response is present for a ConnectException
|
||||
*/
|
||||
class ConnectException extends RequestException
|
||||
{
|
||||
public function __construct(
|
||||
$message,
|
||||
RequestInterface $request,
|
||||
\Exception $previous = null,
|
||||
array $handlerContext = []
|
||||
) {
|
||||
parent::__construct($message, $request, null, $previous, $handlerContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null
|
||||
*/
|
||||
public function getResponse()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function hasResponse()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
interface GuzzleException {}
|
|
@ -1,188 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
|
||||
/**
|
||||
* HTTP Request exception
|
||||
*/
|
||||
class RequestException extends TransferException
|
||||
{
|
||||
/** @var RequestInterface */
|
||||
private $request;
|
||||
|
||||
/** @var ResponseInterface */
|
||||
private $response;
|
||||
|
||||
/** @var array */
|
||||
private $handlerContext;
|
||||
|
||||
public function __construct(
|
||||
$message,
|
||||
RequestInterface $request,
|
||||
ResponseInterface $response = null,
|
||||
\Exception $previous = null,
|
||||
array $handlerContext = []
|
||||
) {
|
||||
// Set the code of the exception if the response is set and not future.
|
||||
$code = $response && !($response instanceof PromiseInterface)
|
||||
? $response->getStatusCode()
|
||||
: 0;
|
||||
parent::__construct($message, $code, $previous);
|
||||
$this->request = $request;
|
||||
$this->response = $response;
|
||||
$this->handlerContext = $handlerContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap non-RequestExceptions with a RequestException
|
||||
*
|
||||
* @param RequestInterface $request
|
||||
* @param \Exception $e
|
||||
*
|
||||
* @return RequestException
|
||||
*/
|
||||
public static function wrapException(RequestInterface $request, \Exception $e)
|
||||
{
|
||||
return $e instanceof RequestException
|
||||
? $e
|
||||
: new RequestException($e->getMessage(), $request, null, $e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create a new exception with a normalized error message
|
||||
*
|
||||
* @param RequestInterface $request Request
|
||||
* @param ResponseInterface $response Response received
|
||||
* @param \Exception $previous Previous exception
|
||||
* @param array $ctx Optional handler context.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function create(
|
||||
RequestInterface $request,
|
||||
ResponseInterface $response = null,
|
||||
\Exception $previous = null,
|
||||
array $ctx = []
|
||||
) {
|
||||
if (!$response) {
|
||||
return new self(
|
||||
'Error completing request',
|
||||
$request,
|
||||
null,
|
||||
$previous,
|
||||
$ctx
|
||||
);
|
||||
}
|
||||
|
||||
$level = floor($response->getStatusCode() / 100);
|
||||
if ($level == '4') {
|
||||
$label = 'Client error';
|
||||
$className = __NAMESPACE__ . '\\ClientException';
|
||||
} elseif ($level == '5') {
|
||||
$label = 'Server error';
|
||||
$className = __NAMESPACE__ . '\\ServerException';
|
||||
} else {
|
||||
$label = 'Unsuccessful request';
|
||||
$className = __CLASS__;
|
||||
}
|
||||
|
||||
// Server Error: `GET /` resulted in a `404 Not Found` response:
|
||||
// <html> ... (truncated)
|
||||
$message = sprintf(
|
||||
'%s: `%s` resulted in a `%s` response',
|
||||
$label,
|
||||
$request->getMethod() . ' ' . $request->getUri(),
|
||||
$response->getStatusCode() . ' ' . $response->getReasonPhrase()
|
||||
);
|
||||
|
||||
$summary = static::getResponseBodySummary($response);
|
||||
|
||||
if ($summary !== null) {
|
||||
$message .= ":\n{$summary}\n";
|
||||
}
|
||||
|
||||
return new $className($message, $request, $response, $previous, $ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a short summary of the response
|
||||
*
|
||||
* Will return `null` if the response is not printable.
|
||||
*
|
||||
* @param ResponseInterface $response
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function getResponseBodySummary(ResponseInterface $response)
|
||||
{
|
||||
$body = $response->getBody();
|
||||
|
||||
if (!$body->isSeekable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = $body->getSize();
|
||||
$summary = $body->read(120);
|
||||
$body->rewind();
|
||||
|
||||
if ($size > 120) {
|
||||
$summary .= ' (truncated...)';
|
||||
}
|
||||
|
||||
// Matches any printable character, including unicode characters:
|
||||
// letters, marks, numbers, punctuation, spacing, and separators.
|
||||
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the request that caused the exception
|
||||
*
|
||||
* @return RequestInterface
|
||||
*/
|
||||
public function getRequest()
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the associated response
|
||||
*
|
||||
* @return ResponseInterface|null
|
||||
*/
|
||||
public function getResponse()
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a response was received
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasResponse()
|
||||
{
|
||||
return $this->response !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get contextual information about the error from the underlying handler.
|
||||
*
|
||||
* The contents of this array will vary depending on which handler you are
|
||||
* using. It may also be just an empty array. Relying on this data will
|
||||
* couple you to a specific handler, but can give more debug information
|
||||
* when needed.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getHandlerContext()
|
||||
{
|
||||
return $this->handlerContext;
|
||||
}
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Exception thrown when a seek fails on a stream.
|
||||
*/
|
||||
class SeekException extends \RuntimeException implements GuzzleException
|
||||
{
|
||||
private $stream;
|
||||
|
||||
public function __construct(StreamInterface $stream, $pos = 0, $msg = '')
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$msg = $msg ?: 'Could not seek the stream to position ' . $pos;
|
||||
parent::__construct($msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return StreamInterface
|
||||
*/
|
||||
public function getStream()
|
||||
{
|
||||
return $this->stream;
|
||||
}
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception when a server error is encountered (5xx codes)
|
||||
*/
|
||||
class ServerException extends BadResponseException {}
|
|
@ -1,4 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
class TooManyRedirectsException extends RequestException {}
|
|
@ -1,4 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
class TransferException extends \RuntimeException implements GuzzleException {}
|
|
@ -1,531 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\Psr7\LazyOpenStream;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Creates curl resources from a request
|
||||
*/
|
||||
class CurlFactory implements CurlFactoryInterface
|
||||
{
|
||||
/** @var array */
|
||||
private $handles;
|
||||
|
||||
/** @var int Total number of idle handles to keep in cache */
|
||||
private $maxHandles;
|
||||
|
||||
/**
|
||||
* @param int $maxHandles Maximum number of idle handles.
|
||||
*/
|
||||
public function __construct($maxHandles)
|
||||
{
|
||||
$this->maxHandles = $maxHandles;
|
||||
}
|
||||
|
||||
public function create(RequestInterface $request, array $options)
|
||||
{
|
||||
if (isset($options['curl']['body_as_string'])) {
|
||||
$options['_body_as_string'] = $options['curl']['body_as_string'];
|
||||
unset($options['curl']['body_as_string']);
|
||||
}
|
||||
|
||||
$easy = new EasyHandle;
|
||||
$easy->request = $request;
|
||||
$easy->options = $options;
|
||||
$conf = $this->getDefaultConf($easy);
|
||||
$this->applyMethod($easy, $conf);
|
||||
$this->applyHandlerOptions($easy, $conf);
|
||||
$this->applyHeaders($easy, $conf);
|
||||
unset($conf['_headers']);
|
||||
|
||||
// Add handler options from the request configuration options
|
||||
if (isset($options['curl'])) {
|
||||
$conf = array_replace($conf, $options['curl']);
|
||||
}
|
||||
|
||||
$conf[CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
|
||||
$easy->handle = $this->handles
|
||||
? array_pop($this->handles)
|
||||
: curl_init();
|
||||
curl_setopt_array($easy->handle, $conf);
|
||||
|
||||
return $easy;
|
||||
}
|
||||
|
||||
public function release(EasyHandle $easy)
|
||||
{
|
||||
$resource = $easy->handle;
|
||||
unset($easy->handle);
|
||||
|
||||
if (count($this->handles) >= $this->maxHandles) {
|
||||
curl_close($resource);
|
||||
} else {
|
||||
// Remove all callback functions as they can hold onto references
|
||||
// and are not cleaned up by curl_reset. Using curl_setopt_array
|
||||
// does not work for some reason, so removing each one
|
||||
// individually.
|
||||
curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
|
||||
curl_setopt($resource, CURLOPT_READFUNCTION, null);
|
||||
curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
|
||||
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
|
||||
curl_reset($resource);
|
||||
$this->handles[] = $resource;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes a cURL transaction, either returning a response promise or a
|
||||
* rejected promise.
|
||||
*
|
||||
* @param callable $handler
|
||||
* @param EasyHandle $easy
|
||||
* @param CurlFactoryInterface $factory Dictates how the handle is released
|
||||
*
|
||||
* @return \GuzzleHttp\Promise\PromiseInterface
|
||||
*/
|
||||
public static function finish(
|
||||
callable $handler,
|
||||
EasyHandle $easy,
|
||||
CurlFactoryInterface $factory
|
||||
) {
|
||||
if (isset($easy->options['on_stats'])) {
|
||||
self::invokeStats($easy);
|
||||
}
|
||||
|
||||
if (!$easy->response || $easy->errno) {
|
||||
return self::finishError($handler, $easy, $factory);
|
||||
}
|
||||
|
||||
// Return the response if it is present and there is no error.
|
||||
$factory->release($easy);
|
||||
|
||||
// Rewind the body of the response if possible.
|
||||
$body = $easy->response->getBody();
|
||||
if ($body->isSeekable()) {
|
||||
$body->rewind();
|
||||
}
|
||||
|
||||
return new FulfilledPromise($easy->response);
|
||||
}
|
||||
|
||||
private static function invokeStats(EasyHandle $easy)
|
||||
{
|
||||
$curlStats = curl_getinfo($easy->handle);
|
||||
$stats = new TransferStats(
|
||||
$easy->request,
|
||||
$easy->response,
|
||||
$curlStats['total_time'],
|
||||
$easy->errno,
|
||||
$curlStats
|
||||
);
|
||||
call_user_func($easy->options['on_stats'], $stats);
|
||||
}
|
||||
|
||||
private static function finishError(
|
||||
callable $handler,
|
||||
EasyHandle $easy,
|
||||
CurlFactoryInterface $factory
|
||||
) {
|
||||
// Get error information and release the handle to the factory.
|
||||
$ctx = [
|
||||
'errno' => $easy->errno,
|
||||
'error' => curl_error($easy->handle),
|
||||
] + curl_getinfo($easy->handle);
|
||||
$factory->release($easy);
|
||||
|
||||
// Retry when nothing is present or when curl failed to rewind.
|
||||
if (empty($easy->options['_err_message'])
|
||||
&& (!$easy->errno || $easy->errno == 65)
|
||||
) {
|
||||
return self::retryFailedRewind($handler, $easy, $ctx);
|
||||
}
|
||||
|
||||
return self::createRejection($easy, $ctx);
|
||||
}
|
||||
|
||||
private static function createRejection(EasyHandle $easy, array $ctx)
|
||||
{
|
||||
static $connectionErrors = [
|
||||
CURLE_OPERATION_TIMEOUTED => true,
|
||||
CURLE_COULDNT_RESOLVE_HOST => true,
|
||||
CURLE_COULDNT_CONNECT => true,
|
||||
CURLE_SSL_CONNECT_ERROR => true,
|
||||
CURLE_GOT_NOTHING => true,
|
||||
];
|
||||
|
||||
// If an exception was encountered during the onHeaders event, then
|
||||
// return a rejected promise that wraps that exception.
|
||||
if ($easy->onHeadersException) {
|
||||
return new RejectedPromise(
|
||||
new RequestException(
|
||||
'An error was encountered during the on_headers event',
|
||||
$easy->request,
|
||||
$easy->response,
|
||||
$easy->onHeadersException,
|
||||
$ctx
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$message = sprintf(
|
||||
'cURL error %s: %s (%s)',
|
||||
$ctx['errno'],
|
||||
$ctx['error'],
|
||||
'see http://curl.haxx.se/libcurl/c/libcurl-errors.html'
|
||||
);
|
||||
|
||||
// Create a connection exception if it was a specific error code.
|
||||
$error = isset($connectionErrors[$easy->errno])
|
||||
? new ConnectException($message, $easy->request, null, $ctx)
|
||||
: new RequestException($message, $easy->request, $easy->response, null, $ctx);
|
||||
|
||||
return new RejectedPromise($error);
|
||||
}
|
||||
|
||||
private function getDefaultConf(EasyHandle $easy)
|
||||
{
|
||||
$conf = [
|
||||
'_headers' => $easy->request->getHeaders(),
|
||||
CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
|
||||
CURLOPT_URL => (string) $easy->request->getUri(),
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_HEADER => false,
|
||||
CURLOPT_CONNECTTIMEOUT => 150,
|
||||
];
|
||||
|
||||
if (defined('CURLOPT_PROTOCOLS')) {
|
||||
$conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
|
||||
}
|
||||
|
||||
$version = $easy->request->getProtocolVersion();
|
||||
if ($version == 1.1) {
|
||||
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
|
||||
} elseif ($version == 2.0) {
|
||||
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
|
||||
} else {
|
||||
$conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
|
||||
}
|
||||
|
||||
return $conf;
|
||||
}
|
||||
|
||||
private function applyMethod(EasyHandle $easy, array &$conf)
|
||||
{
|
||||
$body = $easy->request->getBody();
|
||||
$size = $body->getSize();
|
||||
|
||||
if ($size === null || $size > 0) {
|
||||
$this->applyBody($easy->request, $easy->options, $conf);
|
||||
return;
|
||||
}
|
||||
|
||||
$method = $easy->request->getMethod();
|
||||
if ($method === 'PUT' || $method === 'POST') {
|
||||
// See http://tools.ietf.org/html/rfc7230#section-3.3.2
|
||||
if (!$easy->request->hasHeader('Content-Length')) {
|
||||
$conf[CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
|
||||
}
|
||||
} elseif ($method === 'HEAD') {
|
||||
$conf[CURLOPT_NOBODY] = true;
|
||||
unset(
|
||||
$conf[CURLOPT_WRITEFUNCTION],
|
||||
$conf[CURLOPT_READFUNCTION],
|
||||
$conf[CURLOPT_FILE],
|
||||
$conf[CURLOPT_INFILE]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function applyBody(RequestInterface $request, array $options, array &$conf)
|
||||
{
|
||||
$size = $request->hasHeader('Content-Length')
|
||||
? (int) $request->getHeaderLine('Content-Length')
|
||||
: null;
|
||||
|
||||
// Send the body as a string if the size is less than 1MB OR if the
|
||||
// [curl][body_as_string] request value is set.
|
||||
if (($size !== null && $size < 1000000) ||
|
||||
!empty($options['_body_as_string'])
|
||||
) {
|
||||
$conf[CURLOPT_POSTFIELDS] = (string) $request->getBody();
|
||||
// Don't duplicate the Content-Length header
|
||||
$this->removeHeader('Content-Length', $conf);
|
||||
$this->removeHeader('Transfer-Encoding', $conf);
|
||||
} else {
|
||||
$conf[CURLOPT_UPLOAD] = true;
|
||||
if ($size !== null) {
|
||||
$conf[CURLOPT_INFILESIZE] = $size;
|
||||
$this->removeHeader('Content-Length', $conf);
|
||||
}
|
||||
$body = $request->getBody();
|
||||
$conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
|
||||
return $body->read($length);
|
||||
};
|
||||
}
|
||||
|
||||
// If the Expect header is not present, prevent curl from adding it
|
||||
if (!$request->hasHeader('Expect')) {
|
||||
$conf[CURLOPT_HTTPHEADER][] = 'Expect:';
|
||||
}
|
||||
|
||||
// cURL sometimes adds a content-type by default. Prevent this.
|
||||
if (!$request->hasHeader('Content-Type')) {
|
||||
$conf[CURLOPT_HTTPHEADER][] = 'Content-Type:';
|
||||
}
|
||||
}
|
||||
|
||||
private function applyHeaders(EasyHandle $easy, array &$conf)
|
||||
{
|
||||
foreach ($conf['_headers'] as $name => $values) {
|
||||
foreach ($values as $value) {
|
||||
$conf[CURLOPT_HTTPHEADER][] = "$name: $value";
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the Accept header if one was not set
|
||||
if (!$easy->request->hasHeader('Accept')) {
|
||||
$conf[CURLOPT_HTTPHEADER][] = 'Accept:';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a header from the options array.
|
||||
*
|
||||
* @param string $name Case-insensitive header to remove
|
||||
* @param array $options Array of options to modify
|
||||
*/
|
||||
private function removeHeader($name, array &$options)
|
||||
{
|
||||
foreach (array_keys($options['_headers']) as $key) {
|
||||
if (!strcasecmp($key, $name)) {
|
||||
unset($options['_headers'][$key]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function applyHandlerOptions(EasyHandle $easy, array &$conf)
|
||||
{
|
||||
$options = $easy->options;
|
||||
if (isset($options['verify'])) {
|
||||
if ($options['verify'] === false) {
|
||||
unset($conf[CURLOPT_CAINFO]);
|
||||
$conf[CURLOPT_SSL_VERIFYHOST] = 0;
|
||||
$conf[CURLOPT_SSL_VERIFYPEER] = false;
|
||||
} else {
|
||||
$conf[CURLOPT_SSL_VERIFYHOST] = 2;
|
||||
$conf[CURLOPT_SSL_VERIFYPEER] = true;
|
||||
if (is_string($options['verify'])) {
|
||||
$conf[CURLOPT_CAINFO] = $options['verify'];
|
||||
if (!file_exists($options['verify'])) {
|
||||
throw new \InvalidArgumentException(
|
||||
"SSL CA bundle not found: {$options['verify']}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($options['decode_content'])) {
|
||||
$accept = $easy->request->getHeaderLine('Accept-Encoding');
|
||||
if ($accept) {
|
||||
$conf[CURLOPT_ENCODING] = $accept;
|
||||
} else {
|
||||
$conf[CURLOPT_ENCODING] = '';
|
||||
// Don't let curl send the header over the wire
|
||||
$conf[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['sink'])) {
|
||||
$sink = $options['sink'];
|
||||
if (!is_string($sink)) {
|
||||
$sink = \GuzzleHttp\Psr7\stream_for($sink);
|
||||
} elseif (!is_dir(dirname($sink))) {
|
||||
// Ensure that the directory exists before failing in curl.
|
||||
throw new \RuntimeException(sprintf(
|
||||
'Directory %s does not exist for sink value of %s',
|
||||
dirname($sink),
|
||||
$sink
|
||||
));
|
||||
} else {
|
||||
$sink = new LazyOpenStream($sink, 'w+');
|
||||
}
|
||||
$easy->sink = $sink;
|
||||
$conf[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($sink) {
|
||||
return $sink->write($write);
|
||||
};
|
||||
} else {
|
||||
// Use a default temp stream if no sink was set.
|
||||
$conf[CURLOPT_FILE] = fopen('php://temp', 'w+');
|
||||
$easy->sink = Psr7\stream_for($conf[CURLOPT_FILE]);
|
||||
}
|
||||
|
||||
if (isset($options['timeout'])) {
|
||||
$conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
|
||||
}
|
||||
|
||||
if (isset($options['connect_timeout'])) {
|
||||
$conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
|
||||
}
|
||||
|
||||
if (isset($options['proxy'])) {
|
||||
if (!is_array($options['proxy'])) {
|
||||
$conf[CURLOPT_PROXY] = $options['proxy'];
|
||||
} else {
|
||||
$scheme = $easy->request->getUri()->getScheme();
|
||||
if (isset($options['proxy'][$scheme])) {
|
||||
$host = $easy->request->getUri()->getHost();
|
||||
if (!isset($options['proxy']['no']) ||
|
||||
!\GuzzleHttp\is_host_in_noproxy($host, $options['proxy']['no'])
|
||||
) {
|
||||
$conf[CURLOPT_PROXY] = $options['proxy'][$scheme];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['cert'])) {
|
||||
$cert = $options['cert'];
|
||||
if (is_array($cert)) {
|
||||
$conf[CURLOPT_SSLCERTPASSWD] = $cert[1];
|
||||
$cert = $cert[0];
|
||||
}
|
||||
if (!file_exists($cert)) {
|
||||
throw new \InvalidArgumentException(
|
||||
"SSL certificate not found: {$cert}"
|
||||
);
|
||||
}
|
||||
$conf[CURLOPT_SSLCERT] = $cert;
|
||||
}
|
||||
|
||||
if (isset($options['ssl_key'])) {
|
||||
$sslKey = $options['ssl_key'];
|
||||
if (is_array($sslKey)) {
|
||||
$conf[CURLOPT_SSLKEYPASSWD] = $sslKey[1];
|
||||
$sslKey = $sslKey[0];
|
||||
}
|
||||
if (!file_exists($sslKey)) {
|
||||
throw new \InvalidArgumentException(
|
||||
"SSL private key not found: {$sslKey}"
|
||||
);
|
||||
}
|
||||
$conf[CURLOPT_SSLKEY] = $sslKey;
|
||||
}
|
||||
|
||||
if (isset($options['progress'])) {
|
||||
$progress = $options['progress'];
|
||||
if (!is_callable($progress)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'progress client option must be callable'
|
||||
);
|
||||
}
|
||||
$conf[CURLOPT_NOPROGRESS] = false;
|
||||
$conf[CURLOPT_PROGRESSFUNCTION] = function () use ($progress) {
|
||||
$args = func_get_args();
|
||||
// PHP 5.5 pushed the handle onto the start of the args
|
||||
if (is_resource($args[0])) {
|
||||
array_shift($args);
|
||||
}
|
||||
call_user_func_array($progress, $args);
|
||||
};
|
||||
}
|
||||
|
||||
if (!empty($options['debug'])) {
|
||||
$conf[CURLOPT_STDERR] = \GuzzleHttp\debug_resource($options['debug']);
|
||||
$conf[CURLOPT_VERBOSE] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function ensures that a response was set on a transaction. If one
|
||||
* was not set, then the request is retried if possible. This error
|
||||
* typically means you are sending a payload, curl encountered a
|
||||
* "Connection died, retrying a fresh connect" error, tried to rewind the
|
||||
* stream, and then encountered a "necessary data rewind wasn't possible"
|
||||
* error, causing the request to be sent through curl_multi_info_read()
|
||||
* without an error status.
|
||||
*/
|
||||
private static function retryFailedRewind(
|
||||
callable $handler,
|
||||
EasyHandle $easy,
|
||||
array $ctx
|
||||
) {
|
||||
try {
|
||||
// Only rewind if the body has been read from.
|
||||
$body = $easy->request->getBody();
|
||||
if ($body->tell() > 0) {
|
||||
$body->rewind();
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
$ctx['error'] = 'The connection unexpectedly failed without '
|
||||
. 'providing an error. The request would have been retried, '
|
||||
. 'but attempting to rewind the request body failed. '
|
||||
. 'Exception: ' . $e;
|
||||
return self::createRejection($easy, $ctx);
|
||||
}
|
||||
|
||||
// Retry no more than 3 times before giving up.
|
||||
if (!isset($easy->options['_curl_retries'])) {
|
||||
$easy->options['_curl_retries'] = 1;
|
||||
} elseif ($easy->options['_curl_retries'] == 2) {
|
||||
$ctx['error'] = 'The cURL request was retried 3 times '
|
||||
. 'and did not succeed. The most likely reason for the failure '
|
||||
. 'is that cURL was unable to rewind the body of the request '
|
||||
. 'and subsequent retries resulted in the same error. Turn on '
|
||||
. 'the debug option to see what went wrong. See '
|
||||
. 'https://bugs.php.net/bug.php?id=47204 for more information.';
|
||||
return self::createRejection($easy, $ctx);
|
||||
} else {
|
||||
$easy->options['_curl_retries']++;
|
||||
}
|
||||
|
||||
return $handler($easy->request, $easy->options);
|
||||
}
|
||||
|
||||
private function createHeaderFn(EasyHandle $easy)
|
||||
{
|
||||
if (!isset($easy->options['on_headers'])) {
|
||||
$onHeaders = null;
|
||||
} elseif (!is_callable($easy->options['on_headers'])) {
|
||||
throw new \InvalidArgumentException('on_headers must be callable');
|
||||
} else {
|
||||
$onHeaders = $easy->options['on_headers'];
|
||||
}
|
||||
|
||||
return function ($ch, $h) use (
|
||||
$onHeaders,
|
||||
$easy,
|
||||
&$startingResponse
|
||||
) {
|
||||
$value = trim($h);
|
||||
if ($value === '') {
|
||||
$startingResponse = true;
|
||||
$easy->createResponse();
|
||||
if ($onHeaders) {
|
||||
try {
|
||||
$onHeaders($easy->response);
|
||||
} catch (\Exception $e) {
|
||||
// Associate the exception with the handle and trigger
|
||||
// a curl header write error by returning 0.
|
||||
$easy->onHeadersException = $e;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
} elseif ($startingResponse) {
|
||||
$startingResponse = false;
|
||||
$easy->headers = [$value];
|
||||
} else {
|
||||
$easy->headers[] = $value;
|
||||
}
|
||||
return strlen($h);
|
||||
};
|
||||
}
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
interface CurlFactoryInterface
|
||||
{
|
||||
/**
|
||||
* Creates a cURL handle resource.
|
||||
*
|
||||
* @param RequestInterface $request Request
|
||||
* @param array $options Transfer options
|
||||
*
|
||||
* @return EasyHandle
|
||||
* @throws \RuntimeException when an option cannot be applied
|
||||
*/
|
||||
public function create(RequestInterface $request, array $options);
|
||||
|
||||
/**
|
||||
* Release an easy handle, allowing it to be reused or closed.
|
||||
*
|
||||
* This function must call unset on the easy handle's "handle" property.
|
||||
*
|
||||
* @param EasyHandle $easy
|
||||
*/
|
||||
public function release(EasyHandle $easy);
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* HTTP handler that uses cURL easy handles as a transport layer.
|
||||
*
|
||||
* When using the CurlHandler, custom curl options can be specified as an
|
||||
* associative array of curl option constants mapping to values in the
|
||||
* **curl** key of the "client" key of the request.
|
||||
*/
|
||||
class CurlHandler
|
||||
{
|
||||
/** @var CurlFactoryInterface */
|
||||
private $factory;
|
||||
|
||||
/**
|
||||
* Accepts an associative array of options:
|
||||
*
|
||||
* - factory: Optional curl factory used to create cURL handles.
|
||||
*
|
||||
* @param array $options Array of options to use with the handler
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->factory = isset($options['handle_factory'])
|
||||
? $options['handle_factory']
|
||||
: new CurlFactory(3);
|
||||
}
|
||||
|
||||
public function __invoke(RequestInterface $request, array $options)
|
||||
{
|
||||
if (isset($options['delay'])) {
|
||||
usleep($options['delay'] * 1000);
|
||||
}
|
||||
|
||||
$easy = $this->factory->create($request, $options);
|
||||
curl_exec($easy->handle);
|
||||
$easy->errno = curl_errno($easy->handle);
|
||||
|
||||
return CurlFactory::finish($this, $easy, $this->factory);
|
||||
}
|
||||
}
|
|
@ -1,197 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Returns an asynchronous response using curl_multi_* functions.
|
||||
*
|
||||
* When using the CurlMultiHandler, custom curl options can be specified as an
|
||||
* associative array of curl option constants mapping to values in the
|
||||
* **curl** key of the provided request options.
|
||||
*
|
||||
* @property resource $_mh Internal use only. Lazy loaded multi-handle.
|
||||
*/
|
||||
class CurlMultiHandler
|
||||
{
|
||||
/** @var CurlFactoryInterface */
|
||||
private $factory;
|
||||
private $selectTimeout;
|
||||
private $active;
|
||||
private $handles = [];
|
||||
private $delays = [];
|
||||
|
||||
/**
|
||||
* This handler accepts the following options:
|
||||
*
|
||||
* - handle_factory: An optional factory used to create curl handles
|
||||
* - select_timeout: Optional timeout (in seconds) to block before timing
|
||||
* out while selecting curl handles. Defaults to 1 second.
|
||||
*
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->factory = isset($options['handle_factory'])
|
||||
? $options['handle_factory'] : new CurlFactory(50);
|
||||
$this->selectTimeout = isset($options['select_timeout'])
|
||||
? $options['select_timeout'] : 1;
|
||||
}
|
||||
|
||||
public function __get($name)
|
||||
{
|
||||
if ($name === '_mh') {
|
||||
return $this->_mh = curl_multi_init();
|
||||
}
|
||||
|
||||
throw new \BadMethodCallException();
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if (isset($this->_mh)) {
|
||||
curl_multi_close($this->_mh);
|
||||
unset($this->_mh);
|
||||
}
|
||||
}
|
||||
|
||||
public function __invoke(RequestInterface $request, array $options)
|
||||
{
|
||||
$easy = $this->factory->create($request, $options);
|
||||
$id = (int) $easy->handle;
|
||||
|
||||
$promise = new Promise(
|
||||
[$this, 'execute'],
|
||||
function () use ($id) { return $this->cancel($id); }
|
||||
);
|
||||
|
||||
$this->addRequest(['easy' => $easy, 'deferred' => $promise]);
|
||||
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ticks the curl event loop.
|
||||
*/
|
||||
public function tick()
|
||||
{
|
||||
// Add any delayed handles if needed.
|
||||
if ($this->delays) {
|
||||
$currentTime = microtime(true);
|
||||
foreach ($this->delays as $id => $delay) {
|
||||
if ($currentTime >= $delay) {
|
||||
unset($this->delays[$id]);
|
||||
curl_multi_add_handle(
|
||||
$this->_mh,
|
||||
$this->handles[$id]['easy']->handle
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step through the task queue which may add additional requests.
|
||||
P\queue()->run();
|
||||
|
||||
if ($this->active &&
|
||||
curl_multi_select($this->_mh, $this->selectTimeout) === -1
|
||||
) {
|
||||
// Perform a usleep if a select returns -1.
|
||||
// See: https://bugs.php.net/bug.php?id=61141
|
||||
usleep(250);
|
||||
}
|
||||
|
||||
while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
|
||||
|
||||
$this->processMessages();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs until all outstanding connections have completed.
|
||||
*/
|
||||
public function execute()
|
||||
{
|
||||
$queue = P\queue();
|
||||
|
||||
while ($this->handles || !$queue->isEmpty()) {
|
||||
// If there are no transfers, then sleep for the next delay
|
||||
if (!$this->active && $this->delays) {
|
||||
usleep($this->timeToNext());
|
||||
}
|
||||
$this->tick();
|
||||
}
|
||||
}
|
||||
|
||||
private function addRequest(array $entry)
|
||||
{
|
||||
$easy = $entry['easy'];
|
||||
$id = (int) $easy->handle;
|
||||
$this->handles[$id] = $entry;
|
||||
if (empty($easy->options['delay'])) {
|
||||
curl_multi_add_handle($this->_mh, $easy->handle);
|
||||
} else {
|
||||
$this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a handle from sending and removes references to it.
|
||||
*
|
||||
* @param int $id Handle ID to cancel and remove.
|
||||
*
|
||||
* @return bool True on success, false on failure.
|
||||
*/
|
||||
private function cancel($id)
|
||||
{
|
||||
// Cannot cancel if it has been processed.
|
||||
if (!isset($this->handles[$id])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$handle = $this->handles[$id]['easy']->handle;
|
||||
unset($this->delays[$id], $this->handles[$id]);
|
||||
curl_multi_remove_handle($this->_mh, $handle);
|
||||
curl_close($handle);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function processMessages()
|
||||
{
|
||||
while ($done = curl_multi_info_read($this->_mh)) {
|
||||
$id = (int) $done['handle'];
|
||||
curl_multi_remove_handle($this->_mh, $done['handle']);
|
||||
|
||||
if (!isset($this->handles[$id])) {
|
||||
// Probably was cancelled.
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry = $this->handles[$id];
|
||||
unset($this->handles[$id], $this->delays[$id]);
|
||||
$entry['easy']->errno = $done['result'];
|
||||
$entry['deferred']->resolve(
|
||||
CurlFactory::finish(
|
||||
$this,
|
||||
$entry['easy'],
|
||||
$this->factory
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function timeToNext()
|
||||
{
|
||||
$currentTime = microtime(true);
|
||||
$nextTime = PHP_INT_MAX;
|
||||
foreach ($this->delays as $time) {
|
||||
if ($time < $nextTime) {
|
||||
$nextTime = $time;
|
||||
}
|
||||
}
|
||||
|
||||
return max(0, $currentTime - $nextTime);
|
||||
}
|
||||
}
|
|
@ -1,87 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Represents a cURL easy handle and the data it populates.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class EasyHandle
|
||||
{
|
||||
/** @var resource cURL resource */
|
||||
public $handle;
|
||||
|
||||
/** @var StreamInterface Where data is being written */
|
||||
public $sink;
|
||||
|
||||
/** @var array Received HTTP headers so far */
|
||||
public $headers = [];
|
||||
|
||||
/** @var ResponseInterface Received response (if any) */
|
||||
public $response;
|
||||
|
||||
/** @var RequestInterface Request being sent */
|
||||
public $request;
|
||||
|
||||
/** @var array Request options */
|
||||
public $options = [];
|
||||
|
||||
/** @var int cURL error number (if any) */
|
||||
public $errno = 0;
|
||||
|
||||
/** @var \Exception Exception during on_headers (if any) */
|
||||
public $onHeadersException;
|
||||
|
||||
/**
|
||||
* Attach a response to the easy handle based on the received headers.
|
||||
*
|
||||
* @throws \RuntimeException if no headers have been received.
|
||||
*/
|
||||
public function createResponse()
|
||||
{
|
||||
if (empty($this->headers)) {
|
||||
throw new \RuntimeException('No headers have been received');
|
||||
}
|
||||
|
||||
// HTTP-version SP status-code SP reason-phrase
|
||||
$startLine = explode(' ', array_shift($this->headers), 3);
|
||||
$headers = \GuzzleHttp\headers_from_lines($this->headers);
|
||||
$normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);
|
||||
|
||||
if (!empty($this->options['decode_content'])
|
||||
&& isset($normalizedKeys['content-encoding'])
|
||||
) {
|
||||
unset($headers[$normalizedKeys['content-encoding']]);
|
||||
if (isset($normalizedKeys['content-length'])) {
|
||||
$bodyLength = (int) $this->sink->getSize();
|
||||
if ($bodyLength) {
|
||||
$headers[$normalizedKeys['content-length']] = $bodyLength;
|
||||
} else {
|
||||
unset($headers[$normalizedKeys['content-length']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attach a response to the easy handle with the parsed headers.
|
||||
$this->response = new Response(
|
||||
$startLine[1],
|
||||
$headers,
|
||||
$this->sink,
|
||||
substr($startLine[0], 5),
|
||||
isset($startLine[2]) ? (string) $startLine[2] : null
|
||||
);
|
||||
}
|
||||
|
||||
public function __get($name)
|
||||
{
|
||||
$msg = $name === 'handle'
|
||||
? 'The EasyHandle has been released'
|
||||
: 'Invalid property: ' . $name;
|
||||
throw new \BadMethodCallException($msg);
|
||||
}
|
||||
}
|
|
@ -1,176 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Handler that returns responses or throw exceptions from a queue.
|
||||
*/
|
||||
class MockHandler implements \Countable
|
||||
{
|
||||
private $queue;
|
||||
private $lastRequest;
|
||||
private $lastOptions;
|
||||
private $onFulfilled;
|
||||
private $onRejected;
|
||||
|
||||
/**
|
||||
* Creates a new MockHandler that uses the default handler stack list of
|
||||
* middlewares.
|
||||
*
|
||||
* @param array $queue Array of responses, callables, or exceptions.
|
||||
* @param callable $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param callable $onRejected Callback to invoke when the return value is rejected.
|
||||
*
|
||||
* @return MockHandler
|
||||
*/
|
||||
public static function createWithMiddleware(
|
||||
array $queue = null,
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
|
||||
}
|
||||
|
||||
/**
|
||||
* The passed in value must be an array of
|
||||
* {@see Psr7\Http\Message\ResponseInterface} objects, Exceptions,
|
||||
* callables, or Promises.
|
||||
*
|
||||
* @param array $queue
|
||||
* @param callable $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param callable $onRejected Callback to invoke when the return value is rejected.
|
||||
*/
|
||||
public function __construct(
|
||||
array $queue = null,
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
$this->onFulfilled = $onFulfilled;
|
||||
$this->onRejected = $onRejected;
|
||||
|
||||
if ($queue) {
|
||||
call_user_func_array([$this, 'append'], $queue);
|
||||
}
|
||||
}
|
||||
|
||||
public function __invoke(RequestInterface $request, array $options)
|
||||
{
|
||||
if (!$this->queue) {
|
||||
throw new \OutOfBoundsException('Mock queue is empty');
|
||||
}
|
||||
|
||||
if (isset($options['delay'])) {
|
||||
usleep($options['delay'] * 1000);
|
||||
}
|
||||
|
||||
$this->lastRequest = $request;
|
||||
$this->lastOptions = $options;
|
||||
$response = array_shift($this->queue);
|
||||
|
||||
if (is_callable($response)) {
|
||||
$response = $response($request, $options);
|
||||
}
|
||||
|
||||
$response = $response instanceof \Exception
|
||||
? new RejectedPromise($response)
|
||||
: \GuzzleHttp\Promise\promise_for($response);
|
||||
|
||||
return $response->then(
|
||||
function ($value) use ($request, $options) {
|
||||
$this->invokeStats($request, $options, $value);
|
||||
if ($this->onFulfilled) {
|
||||
call_user_func($this->onFulfilled, $value);
|
||||
}
|
||||
if (isset($options['sink'])) {
|
||||
$contents = (string) $value->getBody();
|
||||
$sink = $options['sink'];
|
||||
|
||||
if (is_resource($sink)) {
|
||||
fwrite($sink, $contents);
|
||||
} elseif (is_string($sink)) {
|
||||
file_put_contents($sink, $contents);
|
||||
} elseif ($sink instanceof \Psr\Http\Message\StreamInterface) {
|
||||
$sink->write($contents);
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
},
|
||||
function ($reason) use ($request, $options) {
|
||||
$this->invokeStats($request, $options, null, $reason);
|
||||
if ($this->onRejected) {
|
||||
call_user_func($this->onRejected, $reason);
|
||||
}
|
||||
return new RejectedPromise($reason);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more variadic requests, exceptions, callables, or promises
|
||||
* to the queue.
|
||||
*/
|
||||
public function append()
|
||||
{
|
||||
foreach (func_get_args() as $value) {
|
||||
if ($value instanceof ResponseInterface
|
||||
|| $value instanceof \Exception
|
||||
|| $value instanceof PromiseInterface
|
||||
|| is_callable($value)
|
||||
) {
|
||||
$this->queue[] = $value;
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Expected a response or '
|
||||
. 'exception. Found ' . \GuzzleHttp\describe_type($value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last received request.
|
||||
*
|
||||
* @return RequestInterface
|
||||
*/
|
||||
public function getLastRequest()
|
||||
{
|
||||
return $this->lastRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last received request options.
|
||||
*
|
||||
* @return RequestInterface
|
||||
*/
|
||||
public function getLastOptions()
|
||||
{
|
||||
return $this->lastOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of remaining items in the queue.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->queue);
|
||||
}
|
||||
|
||||
private function invokeStats(
|
||||
RequestInterface $request,
|
||||
array $options,
|
||||
ResponseInterface $response = null,
|
||||
$reason = null
|
||||
) {
|
||||
if (isset($options['on_stats'])) {
|
||||
$stats = new TransferStats($request, $response, 0, $reason);
|
||||
call_user_func($options['on_stats'], $stats);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Provides basic proxies for handlers.
|
||||
*/
|
||||
class Proxy
|
||||
{
|
||||
/**
|
||||
* Sends synchronous requests to a specific handler while sending all other
|
||||
* requests to another handler.
|
||||
*
|
||||
* @param callable $default Handler used for normal responses
|
||||
* @param callable $sync Handler used for synchronous responses.
|
||||
*
|
||||
* @return callable Returns the composed handler.
|
||||
*/
|
||||
public static function wrapSync(
|
||||
callable $default,
|
||||
callable $sync
|
||||
) {
|
||||
return function (RequestInterface $request, array $options) use ($default, $sync) {
|
||||
return empty($options[RequestOptions::SYNCHRONOUS])
|
||||
? $default($request, $options)
|
||||
: $sync($request, $options);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends streaming requests to a streaming compatible handler while sending
|
||||
* all other requests to a default handler.
|
||||
*
|
||||
* This, for example, could be useful for taking advantage of the
|
||||
* performance benefits of curl while still supporting true streaming
|
||||
* through the StreamHandler.
|
||||
*
|
||||
* @param callable $default Handler used for non-streaming responses
|
||||
* @param callable $streaming Handler used for streaming responses
|
||||
*
|
||||
* @return callable Returns the composed handler.
|
||||
*/
|
||||
public static function wrapStreaming(
|
||||
callable $default,
|
||||
callable $streaming
|
||||
) {
|
||||
return function (RequestInterface $request, array $options) use ($default, $streaming) {
|
||||
return empty($options['stream'])
|
||||
? $default($request, $options)
|
||||
: $streaming($request, $options);
|
||||
};
|
||||
}
|
||||
}
|
|
@ -1,458 +0,0 @@
|
|||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* HTTP handler that uses PHP's HTTP stream wrapper.
|
||||
*/
|
||||
class StreamHandler
|
||||
{
|
||||
private $lastHeaders = [];
|
||||
|
||||
/**
|
||||
* Sends an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send.
|
||||
* @param array $options Request transfer options.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public function __invoke(RequestInterface $request, array $options)
|
||||
{
|
||||
// Sleep if there is a delay specified.
|
||||
if (isset($options['delay'])) {
|
||||
usleep($options['delay'] * 1000);
|
||||
}
|
||||
|
||||
$startTime = isset($options['on_stats']) ? microtime(true) : null;
|
||||
|
||||
try {
|
||||
// Does not support the expect header.
|
||||
$request = $request->withoutHeader('Expect');
|
||||
|
||||
// Append a content-length header if body size is zero to match
|
||||
// cURL's behavior.
|
||||
if (0 === $request->getBody()->getSize()) {
|
||||
$request = $request->withHeader('Content-Length', 0);
|
||||
}
|
||||
|
||||
return $this->createResponse(
|
||||
$request,
|
||||
$options,
|
||||
$this->createStream($request, $options),
|
||||
$startTime
|
||||
);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
// Determine if the error was a networking error.
|
||||
$message = $e->getMessage();
|
||||
// This list can probably get more comprehensive.
|
||||
if (strpos($message, 'getaddrinfo') // DNS lookup failed
|
||||
|| strpos($message, 'Connection refused')
|
||||
|| strpos($message, "couldn't connect to host") // error on HHVM
|
||||
) {
|
||||
$e = new ConnectException($e->getMessage(), $request, $e);
|
||||
}
|
||||
$e = RequestException::wrapException($request, $e);
|
||||
$this->invokeStats($options, $request, $startTime, null, $e);
|
||||
|
||||
return new RejectedPromise($e);
|
||||
}
|
||||
}
|
||||
|
||||
private function invokeStats(
|
||||
array $options,
|
||||
RequestInterface $request,
|
||||
$startTime,
|
||||
ResponseInterface $response = null,
|
||||
$error = null
|
||||
) {
|
||||
if (isset($options['on_stats'])) {
|
||||
$stats = new TransferStats(
|
||||
$request,
|
||||
$response,
|
||||
microtime(true) - $startTime,
|
||||
$error,
|
||||
[]
|
||||
);
|
||||
call_user_func($options['on_stats'], $stats);
|
||||
}
|
||||
}
|
||||
|
||||
private function createResponse(
|
||||
RequestInterface $request,
|
||||
array $options,
|
||||
$stream,
|
||||
$startTime
|
||||
) {
|
||||
$hdrs = $this->lastHeaders;
|
||||
$this->lastHeaders = [];
|
||||
$parts = explode(' ', array_shift($hdrs), 3);
|
||||
$ver = explode('/', $parts[0])[1];
|
||||
$status = $parts[1];
|
||||
$reason = isset($parts[2]) ? $parts[2] : null;
|
||||
$headers = \GuzzleHttp\headers_from_lines($hdrs);
|
||||
list ($stream, $headers) = $this->checkDecode($options, $headers, $stream);
|
||||
$stream = Psr7\stream_for($stream);
|
||||
$sink = $this->createSink($stream, $options);
|
||||
$response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
|
||||
|
||||
if (isset($options['on_headers'])) {
|
||||
try {
|
||||
$options['on_headers']($response);
|
||||
} catch (\Exception $e) {
|
||||
$msg = 'An error was encountered during the on_headers event';
|
||||
$ex = new RequestException($msg, $request, $response, $e);
|
||||
return new RejectedPromise($ex);
|
||||
}
|
||||
}
|
||||
|
||||
if ($sink !== $stream) {
|
||||
$this->drain($stream, $sink);
|
||||
}
|
||||
|
||||
$this->invokeStats($options, $request, $startTime, $response, null);
|
||||
|
||||
return new FulfilledPromise($response);
|
||||
}
|
||||
|
||||
private function createSink(StreamInterface $stream, array $options)
|
||||
{
|
||||
if (!empty($options['stream'])) {
|
||||
return $stream;
|
||||
}
|
||||
|
||||
$sink = isset($options['sink'])
|
||||
? $options['sink']
|
||||
: fopen('php://temp', 'r+');
|
||||
|
||||
return is_string($sink)
|
||||
? new Psr7\Stream(Psr7\try_fopen($sink, 'r+'))
|
||||
: Psr7\stream_for($sink);
|
||||
}
|
||||
|
||||
private function checkDecode(array $options, array $headers, $stream)
|
||||
{
|
||||
// Automatically decode responses when instructed.
|
||||
if (!empty($options['decode_content'])) {
|
||||
$normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);
|
||||
if (isset($normalizedKeys['content-encoding'])) {
|
||||
$encoding = $headers[$normalizedKeys['content-encoding']];
|
||||
if ($encoding[0] == 'gzip' || $encoding[0] == 'deflate') {
|
||||
$stream = new Psr7\InflateStream(
|
||||
Psr7\stream_for($stream)
|
||||
);
|
||||
// Remove content-encoding header
|
||||
unset($headers[$normalizedKeys['content-encoding']]);
|
||||
// Fix content-length header
|
||||
if (isset($normalizedKeys['content-length'])) {
|
||||
$length = (int) $stream->getSize();
|
||||
if ($length == 0) {
|
||||
unset($headers[$normalizedKeys['content-length']]);
|
||||
} else {
|
||||
$headers[$normalizedKeys['content-length']] = [$length];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [$stream, $headers];
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains the source stream into the "sink" client option.
|
||||
*
|
||||
* @param StreamInterface $source
|
||||
* @param StreamInterface $sink
|
||||
*
|
||||
* @return StreamInterface
|
||||
* @throws \RuntimeException when the sink option is invalid.
|
||||
*/
|
||||
private function drain(StreamInterface $source, StreamInterface $sink)
|
||||
{
|
||||
Psr7\copy_to_stream($source, $sink);
|
||||
$sink->seek(0);
|
||||
$source->close();
|
||||
|
||||
return $sink;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a resource and check to ensure it was created successfully
|
||||
*
|
||||
* @param callable $callback Callable that returns stream resource
|
||||
*
|
||||
* @return resource
|
||||
* @throws \RuntimeException on error
|
||||
*/
|
||||
private function createResource(callable $callback)
|
||||
{
|
||||
$errors = null;
|
||||
set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
|
||||
$errors[] = [
|
||||
'message' => $msg,
|
||||
'file' => $file,
|
||||
'line' => $line
|
||||
];
|
||||
return true;
|
||||
});
|
||||
|
||||
$resource = $callback();
|
||||
restore_error_handler();
|
||||
|
||||
if (!$resource) {
|
||||
$message = 'Error creating resource: ';
|
||||
foreach ($errors as $err) {
|
||||
foreach ($err as $key => $value) {
|
||||
$message .= "[$key] $value" . PHP_EOL;
|
||||
}
|
||||
}
|
||||
throw new \RuntimeException(trim($message));
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
private function createStream(RequestInterface $request, array $options)
|
||||
{
|
||||
static $methods;
|
||||
if (!$methods) {
|
||||
$methods = array_flip(get_class_methods(__CLASS__));
|
||||
}
|
||||
|
||||
// HTTP/1.1 streams using the PHP stream wrapper require a
|
||||
// Connection: close header
|
||||
if ($request->getProtocolVersion() == '1.1'
|
||||
&& !$request->hasHeader('Connection')
|
||||
) {
|
||||
$request = $request->withHeader('Connection', 'close');
|
||||
}
|
||||
|
||||
// Ensure SSL is verified by default
|
||||
if (!isset($options['verify'])) {
|
||||
$options['verify'] = true;
|
||||
}
|
||||
|
||||
$params = [];
|
||||
$context = $this->getDefaultContext($request, $options);
|
||||
|
||||
if (isset($options['on_headers']) && !is_callable($options['on_headers'])) {
|
||||
throw new \InvalidArgumentException('on_headers must be callable');
|
||||
}
|
||||
|
||||
if (!empty($options)) {
|
||||
foreach ($options as $key => $value) {
|
||||
$method = "add_{$key}";
|
||||
if (isset($methods[$method])) {
|
||||
$this->{$method}($request, $context, $value, $params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['stream_context'])) {
|
||||
if (!is_array($options['stream_context'])) {
|
||||
throw new \InvalidArgumentException('stream_context must be an array');
|
||||
}
|
||||
$context = array_replace_recursive(
|
||||
$context,
|
||||
$options['stream_context']
|
||||
);
|
||||
}
|
||||
|
||||
$context = $this->createResource(
|
||||
function () use ($context, $params) {
|
||||
return stream_context_create($context, $params);
|
||||
}
|
||||
);
|
||||
|
||||
return $this->createResource(
|
||||
function () use ($request, &$http_response_header, $context) {
|
||||
$resource = fopen($request->getUri(), 'r', null, $context);
|
||||
$this->lastHeaders = $http_response_header;
|
||||
return $resource;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private function getDefaultContext(RequestInterface $request)
|
||||
{
|
||||
$headers = '';
|
||||
foreach ($request->getHeaders() as $name => $value) {
|
||||
foreach ($value as $val) {
|
||||
$headers .= "$name: $val\r\n";
|
||||
}
|
||||
}
|
||||
|
||||
$context = [
|
||||
'http' => [
|
||||
'method' => $request->getMethod(),
|
||||
'header' => $headers,
|
||||
'protocol_version' => $request->getProtocolVersion(),
|
||||
'ignore_errors' => true,
|
||||
'follow_location' => 0,
|
||||
],
|
||||
];
|
||||
|
||||
$body = (string) $request->getBody();
|
||||
|
||||
if (!empty($body)) {
|
||||
$context['http']['content'] = $body;
|
||||
// Prevent the HTTP handler from adding a Content-Type header.
|
||||
if (!$request->hasHeader('Content-Type')) {
|
||||
$context['http']['header'] .= "Content-Type:\r\n";
|
||||
}
|
||||
}
|
||||
|
||||
$context['http']['header'] = rtrim($context['http']['header']);
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
private function add_proxy(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
$options['http']['proxy'] = $value;
|
||||
} else {
|
||||
$scheme = $request->getUri()->getScheme();
|
||||
if (isset($value[$scheme])) {
|
||||
if (!isset($value['no'])
|
||||
|| !\GuzzleHttp\is_host_in_noproxy(
|
||||
$request->getUri()->getHost(),
|
||||
$value['no']
|
||||
)
|
||||
) {
|
||||
$options['http']['proxy'] = $value[$scheme];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function add_timeout(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
$options['http']['timeout'] = $value;
|
||||
}
|
||||
|
||||
private function add_verify(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
if ($value === true) {
|
||||
// PHP 5.6 or greater will find the system cert by default. When
|
||||
// < 5.6, use the Guzzle bundled cacert.
|
||||
if (PHP_VERSION_ID < 50600) {
|
||||
$options['ssl']['cafile'] = \GuzzleHttp\default_ca_bundle();
|
||||
}
|
||||
} elseif (is_string($value)) {
|
||||
$options['ssl']['cafile'] = $value;
|
||||
if (!file_exists($value)) {
|
||||
throw new \RuntimeException("SSL CA bundle not found: $value");
|
||||
}
|
||||
} elseif ($value === false) {
|
||||
$options['ssl']['verify_peer'] = false;
|
||||
$options['ssl']['verify_peer_name'] = false;
|
||||
return;
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Invalid verify request option');
|
||||
}
|
||||
|
||||
$options['ssl']['verify_peer'] = true;
|
||||
$options['ssl']['verify_peer_name'] = true;
|
||||
$options['ssl']['allow_self_signed'] = false;
|
||||
}
|
||||
|
||||
private function add_cert(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
if (is_array($value)) {
|
||||
$options['ssl']['passphrase'] = $value[1];
|
||||
$value = $value[0];
|
||||
}
|
||||
|
||||
if (!file_exists($value)) {
|
||||
throw new \RuntimeException("SSL certificate not found: {$value}");
|
||||
}
|
||||
|
||||
$options['ssl']['local_cert'] = $value;
|
||||
}
|
||||
|
||||
private function add_progress(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
$this->addNotification(
|
||||
$params,
|
||||
function ($code, $a, $b, $c, $transferred, $total) use ($value) {
|
||||
if ($code == STREAM_NOTIFY_PROGRESS) {
|
||||
$value($total, $transferred, null, null);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private function add_debug(RequestInterface $request, &$options, $value, &$params)
|
||||
{
|
||||
if ($value === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
static $map = [
|
||||
STREAM_NOTIFY_CONNECT => 'CONNECT',
|
||||
STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
|
||||
STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
|
||||
STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
|
||||
STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
|
||||
STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
|
||||
STREAM_NOTIFY_PROGRESS => 'PROGRESS',
|
||||
STREAM_NOTIFY_FAILURE => 'FAILURE',
|
||||
STREAM_NOTIFY_COMPLETED => 'COMPLETED',
|
||||
STREAM_NOTIFY_RESOLVE => 'RESOLVE',
|
||||
];
|
||||
static $args = ['severity', 'message', 'message_code',
|
||||
'bytes_transferred', 'bytes_max'];
|
||||
|
||||
$value = \GuzzleHttp\debug_resource($value);
|
||||
$ident = $request->getMethod() . ' ' . $request->getUri();
|
||||
$this->addNotification(
|
||||
$params,
|
||||
function () use ($ident, $value, $map, $args) {
|
||||
$passed = func_get_args();
|
||||
$code = array_shift($passed);
|
||||
fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
|
||||
foreach (array_filter($passed) as $i => $v) {
|
||||
fwrite($value, $args[$i] . ': "' . $v . '" ');
|
||||
}
|
||||
fwrite($value, "\n");
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private function addNotification(array &$params, callable $notify)
|
||||
{
|
||||
// Wrap the existing function if needed.
|
||||
if (!isset($params['notification'])) {
|
||||
$params['notification'] = $notify;
|
||||
} else {
|
||||
$params['notification'] = $this->callArray([
|
||||
$params['notification'],
|
||||
$notify
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function callArray(array $functions)
|
||||
{
|
||||
return function () use ($functions) {
|
||||
$args = func_get_args();
|
||||
foreach ($functions as $fn) {
|
||||
call_user_func_array($fn, $args);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue