Demarrage

This commit is contained in:
Michael RICOIS 2015-09-29 10:09:23 +00:00
parent efe3d6ca04
commit bdce1b423e
2949 changed files with 16957 additions and 708019 deletions

View File

@ -1,25 +1,109 @@
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
//Initialisation global des paramètres de vue
// --- Initialisation global des paramètres de vue
protected function _initViewSettings()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->setEncoding('UTF-8');
$view->doctype('XHTML1_STRICT');
$view->doctype('HTML5');
$view->headMeta()
->appendHttpEquiv('viewport', 'width=device-width, initial-scale=1.0')
->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8')
->appendHttpEquiv('Content-Language', 'fr-FR');
->appendHttpEquiv('Content-Language', 'fr-FR');
//Favicon - Touch icon for iOS 2.0+ and Android 2.1+
$view->headLink()->headLink(array(
'rel' => 'apple-touch-icon-precomposed',
'href' => '/favicon-144.png'
));
//Favicon - targeted to any additional png size
$view->headLink()->headLink(array(
'rel' => 'icon',
'type' => 'image/png',
'href' => '/favicon-32.png'
));
$view->headLink()->headLink(array(
'rel' => 'shortcut icon',
'type' => 'image/x-icon',
'href' => '/favicon.ico')
);
$view->headLink()
->appendStylesheet('/themes/default/css/main.css', 'all')
->appendStylesheet('/libs/bootstrap-3.3.4/css/bootstrap.min.css', 'all');
$view->headScript()
->appendFile('/libs/html5shiv.min.js', 'text/javascript', array('conditional' => 'lt IE 9'))
->appendFile('/libs/respond.min.js', 'text/javascript', array('conditional' => 'lt IE 9'));
$view->inlineScript()
->appendFile('/libs/jquery-2.1.4.min.js', 'text/javascript')
->appendFile('/libs/bootstrap-3.3.4/js/bootstrap.min.js', 'text/javascript');
$view->headTitle()->setSeparator(' - ');
$view->headTitle('Filer');
$view->headTitle('WebFiler');
}
//Initialisation global des paramètres de log
protected function _initLogging()
{
//Firebug
$writer = new Zend_Log_Writer_Firebug();
if(APPLICATION_ENV=='production') {
$writer->setEnabled(false);
}
$logger = new Zend_Log($writer);
Zend_Registry::set('firebug', $logger);
}
protected function _initDb()
{
$c = new Zend_Config($this->getOptions());
try {
$db = Zend_Db::factory($c->resources->db);
$db->getConnection();
} catch ( Exception $e ) {
if (APPLICATION_ENV == 'development') {
echo '<pre>'; print_r($e); echo '</pre>';
} else {
echo "Le service rencontre actuellement un problème technique.";
}
exit;
}
/**
* Set the default adapter to use with all model
*/
Zend_Db_Table::setDefaultAdapter($db);
/**
* Set Firebug Database profiler
*/
if (APPLICATION_ENV == 'development') {
$profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
$profiler->setEnabled(true);
$db->setProfiler($profiler);
}
return $db;
}
protected function _initCache()
{
if ( APPLICATION_ENV!='development' ) {
//MetadataCache pour la base de données
$frontendOptions = array(
'lifetime' => 14400,
'automatic_serialization' => true
);
$backendOptions = array();
$cache = Zend_Cache::factory('Core','Apc', $frontendOptions, $backendOptions);
Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
}
}
}

View File

@ -1,28 +0,0 @@
[production]
phpSettings.date.timezone = "Europe/Paris"
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
autoloaderNamespaces[] = "Application_"
resources.layout.layout = "main"
resources.layout.layoutPath = APPLICATION_PATH "/views"
resources.view.basePath = APPLICATION_PATH "/views"
[staging : production]
resources.frontController.params.displayExceptions = 0
phpSettings.soap.wsdl_cache_enabled = 0
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
phpSettings.soap.wsdl_cache_enabled = 0
resources.frontController.params.displayExceptions = 1
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

View File

@ -0,0 +1,4 @@
<?php
return array(
);

View File

@ -1,6 +0,0 @@
<?php
class DashboardController extends Zend_Controller_Action
{
public function indexAction(){}
}

View File

@ -1,9 +0,0 @@
<?php
class EnvoiController extends Zend_Controller_Action
{
public function manuelAction(){}
public function autoAction(){}
}

View File

@ -0,0 +1,64 @@
<?php
class ErrorController extends Zend_Controller_Action
{
public function init(){}
public function errorAction()
{
$params = $this->getRequest()->getParams();
$unknow = array('MSOffice', '_vti_bin', 'crossdomain.xml');
if (in_array($params['controller'], $unknow)){
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
echo '';
} else {
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$this->view->message = 'Application error';
break;
}
// Log exception, if logger available
if ($log = $this->getLog()) {
$log->crit($this->view->message, $errors->exception);
}
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
$this->view->exception = $errors->exception;
}
$this->view->request = $errors->request;
}
}
public function soapAction(){}
public function permsAction(){}
public function paramsAction(){}
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasPluginResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
}
}

View File

@ -1,6 +0,0 @@
<?php
class FichierController extends Zend_Controller_Action
{
public function indexAction(){}
}

View File

@ -0,0 +1,62 @@
<?php
class UserController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout()->disableLayout();
}
public function loginAction()
{
$this->_helper->layout()->disableLayout();
$this->view->headLink()
->appendStylesheet('/themes/default/css/signin.css', 'all');
$this->view->headTitle()->append('Connexion');
$form = new Application_Form_Login();
$this->view->form = $form;
$request = $this->getRequest();
if ($request->isPost()) {
$formData = $request->getPost();
if ($form->isValid($formData)) {
$login = $form->getValue('login');
$pass = $form->getValue('pass');
$auth = Zend_Auth::getInstance();
$authAdapter = new Scores_Auth_Adapter_Db($login, $pass);
$result = $auth->authenticate($authAdapter);
if ( $result->isValid() ) {
//$timeout = $auth->getIdentity()->timeout;
$timeout = 86400;
//Ecrit un cookie persistant valide pendant le temps definit
Zend_Session::rememberMe($timeout);
$storage = new Zend_Auth_Storage_Session();
$sessionNamespace = new Zend_Session_Namespace($storage->getNamespace());
$sessionNamespace->setExpirationSeconds($timeout);
$auth->setStorage($storage);
$this->redirect('/');
} else {
$this->view->message = '';
foreach ($result->getMessages() as $message) {
$this->view->message.= $message."<br/>";
}
}
}
}
}
public function logoutAction()
{
$this->_helper->layout()->disableLayout();
Zend_Auth::getInstance()->clearIdentity();
}
}

View File

@ -0,0 +1,3 @@
<div class="container">
<p class="text-muted credit"> &copy; <?=date('Y')?> <a href="http://www.scores-decisions.com">Scores &amp; Décisions</a>.</p>
</div>

View File

@ -0,0 +1,45 @@
<!-- Fixed navbar -->
<div class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?=$this->url(array('controller'=>'index', 'action'=>'index'), null, true)?>">Backoffice</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<?php foreach ($this->navigation()->getContainer() as $page) {?>
<li class="dropdown<?php if ( $page->isActive(true) ) { echo ' active'; } ?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?=$page->label?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="<?=$page->getHref()?>">Accueil</a></li>
<li class="divider"></li>
<?php if ( $page->hasPages() ) {?>
<?php foreach ( $page->getPages() as $child ) {?>
<?php if ( $child->getHref() == '#') {?>
<li class="divider"></li>
<?php } else {?>
<li <?php if ( $child->isActive(true) ) { echo "class='active'"; } ?>><a href="<?=$child->getHref()?>"><?=$child->label?></a></li>
<?php }?>
<?php }?>
<?php }?>
</ul>
</li>
<?php }?>
</ul>
<p class="navbar-text pull-right"><?=$this->profileLink()?></p>
</div><!--/.nav-collapse -->
</div>
</div>
<!-- Breadcrumbs -->
<?php if ($this->navigation()->breadcrumbs() != '') {?>
<div class="container-fluid">
<ol class="breadcrumb">
<?php echo $this->navigation()->breadcrumbs()->setLinkLast(false)->setSeparator(' / '); ?>
</ol>
</div>
<?php }?>

View File

@ -0,0 +1,24 @@
<?php echo $this->doctype(); ?>
<html>
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headStyle(); ?>
<?php echo $this->headLink(); ?>
<?php echo $this->headScript(); ?>
</head>
<body>
<div id="wrap">
<?php echo $this->render('header.phtml') ?>
<?php echo $this->layout()->content; ?>
</div>
<div id="footer">
<?php echo $this->render('footer.phtml'); ?>
</div>
<?php echo $this->inlineScript(); ?>
</body>
</html>

View File

@ -1,17 +0,0 @@
<?php echo $this->doctype();?>
<html>
<head>
<?php echo $this->headMeta();?>
<?php echo $this->headTitle();?>
<?php echo $this->headStyle();?>
<?php echo $this->headLink();?>
<?php echo $this->headScript();?>
</head>
<body>
<div id="global">
<div id="content">
<?php echo $this->layout()->content;?>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,29 @@
<div class="container-fluid">
<h1>Erreur</h1>
<div class="paragraph">
<b><?php echo $this->message ?></b>
</div>
<?php if (isset($this->exception)): ?>
<h2>Exception information:</h2>
<div class="paragraph">
<p>
<b>Message:</b> <pre><?php echo $this->exception->getMessage() ?></pre>
</p>
</div>
<br/>
<h2>Stack trace:</h2>
<div class="paragraph">
<pre><?php echo $this->exception->getTraceAsString() ?></pre>
</div>
<br/>
<h2>Request Parameters:</h2>
<div class="paragraph">
<pre><?php echo var_export($this->request->getParams(), true) ?></pre>
</div>
<?php endif ?>
</div>

View File

@ -0,0 +1,28 @@
<?php echo $this->doctype(); ?>
<html>
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headStyle(); ?>
<?php echo $this->headLink(); ?>
<?php echo $this->headScript(); ?>
</head>
<body>
<div id="wrap">
<div class="container">
<form class="form-signin" method="<?=$this->form->getMethod()?>" action="<?=$this->form->getAction()?>">
<h2 class="form-signin-heading">Backoffice</h2>
<input name="login" value="<?=$this->form->getValue('login')?>" type="text" class="form-control" placeholder="Identifiant" autofocus>
<input name="pass" value="<?=$this->form->getValue('pass')?>" type="password" class="form-control" placeholder="Mot de passe">
<button class="btn btn-lg btn-primary btn-block" type="submit">Connexion</button>
</form>
</div>
</div>
<?php echo $this->inlineScript(); ?>
</body>
</html>

View File

@ -0,0 +1,25 @@
<?php if ($this->ajax) {?>
<h4 class="logout">Vous avez été déconnecté.</h4>
<h5 class="logout">Veuillez cliquer <a href="<?=$this->url?>">ici</a>
</h5>
<?php } else {?>
<?php echo $this->doctype()?>
<html>
<head>
<?=$this->headMeta();?>
<?=$this->headTitle();?>
</head>
<body>
<h4 class="logout">Vous avez été déconnecté.</h4>
<p><?=$this->message?></p>
<h5 class="logout">
Si cette page ne disparait pas au bout de <?=$this->refresh?> seconde(s),
veuillez cliquer <a href="<?=$this->url?>">ici</a>
</h5>
</body>
</html>
<?php }?>

21
composer.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "scores/webfiler",
"description": "Distribution des fichiers",
"require": {
"zendframework/zendframework1": "^1.12"
},
"include-path": ["library/"],
"autoload": {
"classmap": [
"application/",
"library/Application/",
"library/Scores/",
]
},
"authors": [
{
"name": "Scores et Decisions",
"email": "supportdev@scores-decisions.com"
}
]
}

View File

@ -0,0 +1,98 @@
<?php
class Application_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
/**
* Vérifie les autorisations
* Utilise _request et _response hérités et injectés par le FC
*
* @param Zend_Controller_Request_Abstract $request : non utilisé, mais demandé par l'héritage
*/
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = $request->getControllerName();
$action = $request->getActionName();
$checkAuth = true;
// --- Pas d'authentification sur la demande d'authentification
if ( $controller == 'user' && $action == 'login' ) {
$checkAuth = false;
}
// --- Pas d'authentification sur ces services
if ( in_array($controller, array('service', 'import'))
|| ( $controller == 'fichier' && $action == 'logs' )
|| ( $controller == 'fichier' && $action == 'kbis' )
|| ( $controller == 'fichier' && $action == 'csv' )
|| ( $controller == 'fichier' && $action == 'associations' )
|| ( $controller == 'fichier' && $action == 'greffes' )
|| ( $controller == 'fichier' && $action == 'crm' )) {
$checkAuth = false;
}
$checkWs = true;
if ( $controller == 'fichier' ) {
$checkWs = false;
}
if ($checkAuth) {
$login = $request->getParam('login');
$pass = $request->getParam('pass', '');
$hach = $request->getParam('hach');
if (!empty($hach)) {
$pass = $hach;
}
$auth = Zend_Auth::getInstance();
// --- On vérifie le tout lors d'une connexion par url
if ( !empty($login) && !empty($pass) ) {
$authAdapter = new Scores_Auth_Adapter_Db($login, $pass, $checkWs);
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$storage = new Zend_Auth_Storage_Session();
$session = new Zend_Session_Namespace($storage->getNamespace());
//$session->setExpirationSeconds(86400);
$auth->setStorage($storage);
} else {
$layout = Zend_Layout::getMVCInstance();
if ( !$layout->isEnabled() ){
echo "Identification incorrect ou périmé.";
} else {
$request->setModuleName('default')
->setControllerName('user')
->setActionName('logout');
}
}
//Sinon on reste sur le standard
} else {
//Pas authentifié
if ( !$auth->hasIdentity() || time() > $auth->getIdentity()->time ) {
$layout = Zend_Layout::getMVCInstance();
if (!$layout->isEnabled()){
echo "Identification incorrect ou périmé.";
} else {
$this->_response->setRedirect('/user/login')->sendResponse();
}
//Authentifié => on met à jour la session
} else {
$identity = $auth->getIdentity();
$identity->time = time() + $identity->timeout;
$auth->getStorage()->write($identity);
}
}
}
}
}

View File

@ -0,0 +1,28 @@
<?php
class Application_Form_Login extends Zend_Form {
public function init()
{
$this->setName('login');
$this->setAction('login');
$this->setMethod('post');
$this->addElement('text', 'login', array(
'filters' => array('StringTrim'),
'label' => 'Identifiant : ',
'required' => 'true',
)
);
$this->addElement('password', 'pass',
array(
'label' => 'Mot de passe : ',
'required' => 'true',
)
);
$this->addElement('submit', 'submit',
array(
'label' => 'Identification',
'ignore' => true,
));
}
}

View File

@ -0,0 +1,102 @@
<?php
class Scores_Auth_Adapter_Db implements Zend_Auth_Adapter_Interface
{
protected $_username;
protected $_password;
protected $_hash;
protected $_timeout = 3600;
protected $checkWs = false;
protected $clients = array();
/**
*
* @param string $username
* @param string $password
* @param boolean $checkWs
*/
public function __construct($username, $password, $checkWs = false)
{
$this->_username = $username;
$this->_password = $password;
$this->_hash = md5($username.'|'.$password);
$this->checkWs = $checkWs;
}
/**
* Limit access to only client IDs
* @param array $id
*/
public function limitClient($id = null)
{
if (is_array($id) && count($id)>0) {
$this->clients = $id;
}
}
/**
* Override the timeout
* @param integer $seconds
*/
public function setTimeout($seconds = null)
{
if ($seconds===null)
return;
$this->_timeout = $seconds;
}
/**
* (non-PHPdoc)
* @see Zend_Auth_Adapter_Interface::authenticate()
*/
public function authenticate()
{
$userM = new Application_Model_Sdv1Utilisateurs();
$sql = $userM->select()
->setIntegrityCheck(false)
->from(array('u'=>'sdv1.utilisateurs'), array('u.idClient', 'u.id', 'u.login', 'u.password'))
->join(array('c'=>'sdv1.clients'), 'u.idClient = c.id', array('c.timeout'))
->where('u.login=?', $this->_username)
->where('u.actif=?', 1)
->where('u.deleted=?', 0)
->where('c.actif=?','Oui');
if ( count($this->clients) > 0 ) {
$sql->where('u.idClient IN('.join(',',$this->clients).')');
}
if ($this->checkWs) {
$sql->where('u.accesWS=?',1);
}
$result = $userM->fetchRow($sql);
$identity = new stdClass();
$identity->username = $this->_username;
$identity->hash = $this->_hash;
if ( null === $result ) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $identity);
} else {
if ( $this->_password == $result->password
|| $this->_password == md5($result->login.'|'.$result->password) ) {
$identity->id = $result->id;
$identity->idClient = $result->idClient;
$timeout = (!empty($result->timeout)) ? $result->timeout : $this->_timeout;
$identity->timeout = $timeout;
$identity->time = time() + $timeout;
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
} else {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $identity);
}
}
}
}

View File

@ -0,0 +1,179 @@
<?php
class Scores_Auth_Adapter_Ws implements Zend_Auth_Adapter_Interface
{
/**
*
* @var string
*/
protected $_username;
/**
*
* @var string
*/
protected $_password;
/**
*
* @var unknown
*/
protected $_timeout = 1800;
/**
*
* @var unknown
*/
protected $_checkIp = false;
public function __construct($username, $password, $iponly = false)
{
$this->_username = $username;
$this->_password = $password;
if ($iponly){
$this->_password = 'iponly:'.$_SERVER['REMOTE_ADDR'];
}
$this->_checkIp = $iponly;
}
/**
* (non-PHPdoc)
* @see Zend_Auth_Adapter_Interface::authenticate()
*/
public function authenticate()
{
$adressIp = $_SERVER['REMOTE_ADDR'];
require_once 'Scores/WsScores.php';
$ws = new WsScores($this->_username, $this->_password);
$InfosLogin = $ws->getInfosLogin($this->_username, $adressIp);
$identity = new stdClass();
$identity->username = $this->_username;
$identity->password = $this->_password;
$identity->email = $InfosLogin->result->email;
$identity->profil = $InfosLogin->result->profil;
$identity->pref = $InfosLogin->result->pref;
$identity->droits = $InfosLogin->result->droits;
$identity->droitsClients = $InfosLogin->result->droitsClients;
$identity->nom = $InfosLogin->result->nom;
$identity->prenom = $InfosLogin->result->prenom;
$identity->tel = $InfosLogin->result->tel;
$identity->fax = $InfosLogin->result->fax;
$identity->mobile = $InfosLogin->result->mobile;
$identity->id = $InfosLogin->result->id;
$identity->idClient = $InfosLogin->result->idClient;
$identity->reference = $InfosLogin->result->reference;
$identity->nbReponses = $InfosLogin->result->nbReponses;
$identity->typeScore = $InfosLogin->result->typeScore;
$identity->dateValidation = $InfosLogin->result->dateValidation;
$identity->nombreConnexions = $InfosLogin->result->nombreConnexions;
$identity->dateDerniereConnexion = $InfosLogin->result->dateDerniereConnexion;
$identity->dateDebutCompte = $InfosLogin->result->dateDebutCompte;
$identity->dateFinCompte = $InfosLogin->result->dateFinCompte;
$identity->acceptationCGU = $InfosLogin->result->acceptationCGU;
$identity->ip = $adressIp;
$identity->modeEdition = false;
$timeout = (!empty($InfosLogin->result->timeout)) ? $InfosLogin->result->timeout : $this->_timeout;
$identity->timeout = $timeout;
$identity->time = time() + $timeout;
$lang = in_array($InfosLogin->result->lang, array('fr','en')) ? $InfosLogin->result->lang : 'fr';
$identity->lang = $lang;
$identity->langtmp = $lang;
/*
* Adresse Ip interdites
*/
$ipInterdites =
'81.252.88.0-81.252.88.7' // CTE D AGGLOMERATION DE SOPHIA
. ';' . '195.200.187.163' // PacWan
. ';' . '213.11.81.41' // Verizon France SAS
. ';' . '83.206.171.252' // FR-BASE-D-INFORMATIONS-LEGALES-BI
. ';' . '81.255.32.139'
. ';' . '212.155.191.1*' // Satair A/S
. ';' . '217.70.1*.17' // OJSC "Sibirtelecom"
. ';' . '212.37.196.156' // GENERALE-MULTIMEDIA-SUD
. ';' . '80.245.60.121' // Planete Marseille - Mailclub
. ';' . '213.246.57.101' // IKOULA
. ';' . '193.104.158.0-193.104.158.255' // Altares.fr
. ';' . '195.6.3.0-195.6.3.255' // ORT
. ';' . '217.144.112.0-217.144.116.63' // Coface
;
if ( $this->checkPlagesIp($ipInterdites, $adressIp) ) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_UNCATEGORIZED, $identity);
}
// Renvoi
if ( is_string($InfosLogin) || $InfosLogin->error->errnum!=0){
$message = $InfosLogin;
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $identity, array($message));
} elseif ($this->_username == $InfosLogin->result->login) {
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
} else {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_UNCATEGORIZED, $identity);
}
}
/**
* Controle si une adresse IP est dans une liste des IP communiquées sous la forme
* 192.168.3.5-192.68.3.10;192.168.3.*;192.168.3.10
* @param string $strPlageIP
* La plage d'adresses IP
* @param string $adresseIP
* L'adresse IP à tester
* @return boolean
*/
protected function checkPlagesIp($strPlageIP, $adresseIP)
{
$connected = false;
$tabIpAllowed = explode(';', trim($strPlageIP));
if (count($tabIpAllowed)==1 && $tabIpAllowed[0]=='') $tabIpAllowed = array();
foreach ($tabIpAllowed as $ip) {
$tabPlages = explode('-', $ip);
// C'est une plage d'adresse '-'
if (isset($tabPlages[1]))
$connected = $this->in_plage($tabPlages[0],$tabPlages[1],$adresseIP);
else {
// C'est une adresse avec ou sans masque '*'
if (preg_match('/^'.str_replace('*','.*',str_replace('.','\.',$ip)).'$/', $adresseIP) )
$connected=true;
}
if ($connected) break;
}
if (count($tabIpAllowed)==0) return false;
elseif (!$connected) {
return false;
}
return true;
}
/**
* Enter description here ...
* @param unknown_type $plage_1
* @param unknown_type $plage_2
* @param unknown_type $ip
* @return boolean
*/
protected function in_plage($plage_1,$plage_2,$ip)
{
$ip2 = $this->getIpNumber($ip);
if ($ip2>=$this->getIpNumber($plage_1) && $ip2<=$this->getIpNumber($plage_2))
return true;
else
return false;
}
/**
* Converti une IP en nombre
* @param string $ip Adresse IP
* @return integer
*/
protected function getIpNumber($ip)
{
$tab=explode('.', $ip);
return (($tab[0]*256*256*256) + ($tab[1]*256*256) + ($tab[2]*256) + ($tab[3]));
}
}

View File

@ -0,0 +1,102 @@
<?php
class Configure
{
/**
* Configuration object
* @var Zend_Config_Ini
*/
protected $profil;
public function __construct()
{
$this->readConfig();
$this->_defineDb();
$this->_definePath();
$this->_defineSphinx();
$this->_defineMail();
}
/**
* Read config application.ini
*/
protected function readConfig()
{
if ( Zend_Registry::isRegistered('config') ) {
$c = Zend_Registry::get('config');
$this->profil = $c->profil;
} else {
$c = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$this->profil = $c->profil;
}
}
protected function _defineDb()
{
$c = Zend_Registry::get('config');
if ( $c->resources->db ) {
define('MYSQL_HOST', $c->resources->db->params->host);
define('MYSQL_USER', $c->resources->db->params->username);
define('MYSQL_PASS', $c->resources->db->params->password);
define('MYSQL_DEFAULT_DB', 'jo');
define('MYSQL_SQL_LOG', 'NONE');
}
}
protected function _definePath()
{
//Use of realpath
define('BODACC_LOCAL_DIR' , '/home/data/bodacc/');
define('JAL_LOCAL_DIR' , '/home/data/jal/');
define('HUGIN_LOCAL_DIR' , '/home/data/infosreg/hugin/');
define('ACTUSNEWS_LOCAL_DIR' , '/home/data/infosreg/actusnews/');
define('DIRELEASE_LOCAL_DIR' , '/home/data/infosreg/direlease/');
define('LESECHOS_LOCAL_DIR' , '/home/data/infosreg/lesechos/');
define('BUSINESSWIRE_LOCAL_DIR_INCOMING' , '/home/data/ftp/businesswire/');
define('BUSINESSWIRE_LOCAL_DIR' , '/home/data/infosreg/businesswire/');
define('SECURE_STORAGE' , $this->profil->path->secure.'/');
define('DOC_WEB_LOCAL' , $this->profil->path->files.'/');
define('DOC_WEB_URL' , '/fichier/');
define('LOG_PATH' , $this->profil->path->data.'/log');
}
protected function _defineSphinx()
{
// Entreprise
define('SPHINX_ENT_HOST', $this->profil->sphinx->ent->host);
define('SPHINX_ENT_PORT', intval($this->profil->sphinx->ent->port));
define('SPHINX_ENT_VERSION', $this->profil->sphinx->ent->version);
// Dirigeants
define('SPHINX_DIR_HOST', $this->profil->sphinx->dir->host);
define('SPHINX_DIR_PORT', intval($this->profil->sphinx->dir->port));
define('SPHINX_DIR_VERSION', $this->profil->sphinx->dir->version);
// Historique
define('SPHINX_HISTO_HOST', $this->profil->sphinx->histo->host);
define('SPHINX_HISTO_PORT', intval($this->profil->sphinx->histo->port));
define('SPHINX_HISTO_VERSION', $this->profil->sphinx->histo->version);
// Actionnaire
define('SPHINX_ACT_HOST', $this->profil->sphinx->act->host);
define('SPHINX_ACT_PORT', intval($this->profil->sphinx->act->port));
define('SPHINX_ACT_VERSION', $this->profil->sphinx->act->version);
//Old
define('SPHINX_HOST', $this->profil->sphinx->ent->host);
define('SPHINX_PORT', intval($this->profil->sphinx->ent->port));
}
protected function _defineMail()
{
//Messagerie
define('SMTP_HOST', $this->profil->mail->smtp_host);
define('SMTP_PORT', '');
define('SMTP_USER', '');
define('SMTP_PASS', '');
}
}

View File

@ -0,0 +1,103 @@
<?php
class Scores_Conso_Export
{
//Extraction des logs payants
//Extraction des logs bruts
protected $entete = array(
'login' => "Identifiant",
'referenceParDefaut' => "Service",
'page' => "Code Requete",
'pageLib' => "Libellé Requete",
'params' => "Paramètres",
'siren' => "Siren",
'nic' => "Nic",
'raisonSociale' => "Raison Sociale",
'cp' => "CP",
'ville' => "Ville",
'dateHeure' => "DateHeure",
'nbDoublon' => "Nb Doublon",
);
protected $pageLib = array();
protected $data = array();
public function __construct()
{
$this->setPageLib();
}
public function setData($d)
{
$this->data = $d;
}
/**
* Formattage des données pour le CSV
* @param string $filename
* @param string $addEntete
*/
public function export($filename, $addEntete = true)
{
$enteteCode = array_keys($this->entete);
$enteteLabel = array_values($this->entete);
$logs = array();
foreach ($this->data as $data){
$row = array();
foreach ($enteteCode as $entete) {
// La colonne existe dans les données
if (array_key_exists($entete, $data)) {
$row[] = $data[$entete];
}
// La colonne existe dans les propriétés
else if (property_exists($this, $entete)){
$code = str_replace('Lib', '', $entete);
$row[] = $this->{$entete}[$data[$code]];
} else {
$row[] = '';
}
}
$logs[] = $row;
}
if ($addEntete && count($this->entete) > 0) {
$export = array_merge(array(0 => $enteteLabel), $logs);
} else {
$export = $logs;
}
$this->exportCSV($export, $filename);
}
/**
* Création du fichier CSV
* @param array $list
* @param string $filename
* @param string $delimiter
*/
protected function exportCSV($list, $filename, $delimiter=',')
{
$fp = fopen($filename, 'w');
foreach($list as $fields){
fputcsv($fp, $fields, $delimiter);
}
fclose($fp);
}
/**
* Récupération des libellés de requete
*/
protected function setPageLib()
{
$libM = new Application_Model_Sdv1LogsItem();
$libSql = $libM->select()->from($libM, array('Code', 'Label'));
$libResult = $libM->fetchAll($libSql);
if (count($libResult) > 0) {
foreach ($libResult as $l) {
$this->pageLib[$l->Code] = $l->Label;
}
}
}
}

View File

@ -0,0 +1,135 @@
<?php
/**
* Comptabilise le nombre d'entité d'un fichier
*/
class Scores_Conso_File
{
protected $login = array();
protected $date;
protected $item;
/**
* @var Zend_Db_Table_Abstract
*/
protected $table;
/**
*
* @var Zend_Db_Select
*/
protected $sql;
/**
*
* @param Zend_Db_Table_Abstract $table
*/
public function __construct(Zend_Db_Table_Abstract $table)
{
$this->table = $table;
$this->sql = $this->table->select();
}
/**
* Array of login
* @param array $login
*/
public function setLogin($login)
{
$this->login = $login;
}
/**
* Date au format AAAAMM
* @param string $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Code de l'élément à compter
* @param string $item
*/
public function setItem($item)
{
$this->item = $item;
}
/**
* Retourne la requete
* @return Zend_Db_Select
*/
public function getSqlRule()
{
$this->addSqlLogin();
$this->addSqlItem();
$this->addSqlDate();
return $this->sql;
}
/**
*
* @param unknown $name
* @param unknown $value
*/
public function setOption($name, $value)
{
if ( null === $this->item ) {
return new Zend_Exception('Item is not set !');
}
if ($name == 'duplicate') {
if ( !array_key_exists('duplicate', $this->rules[$this->item]) ) {
switch ( strtolower($value) ) {
case 'day':
case 'jour':
$this->rules[$this->item]['duplicate'] = 'day';
break;
case 'month':
case 'mois':
case 'period':
case 'periode':
$this->rules[$this->item]['duplicate'] = 'period';
break;
}
}
}
}
/**
*
*/
public function addSqlLogin()
{
$this->sql->where("login IN ('".join("','", $this->login)."')");
}
public function addSqlDate()
{
$formatedDate = substr($this->date,0,4).'-'.substr($this->date,4,2);
$this->sql->where("dateAjout BETWEEN '".$formatedDate."-01 00:00:00' AND '".$formatedDate."-31 23:59:59'");
}
public function addSqlItem()
{
$this->sql->from($this->table, array('COUNT(*) AS NB'));
$rule = $this->rules[$this->item];
//Apply item parameters
/*if ( array_key_exists('params', $rule) && count($rule['params'])>0 ) {
foreach ( $rule['params'] as $param ) {
$this->sql->where($param);
}
}*/
$this->sql->where('source=?', $this->item);
$this->sql->order('dateAjout ASC');
}
}

View File

@ -0,0 +1,66 @@
<?php
class Scores_Conso_Flux
{
protected $code;
protected $date;
protected $dateStock = false;
/**
* @var Zend_Db_Table_Abstract
*/
protected $table;
/**
*
* @var Zend_Db_Select
*/
protected $sql;
/**
*
* @param Zend_Db_Table_Abstract $table
*/
public function __construct(Zend_Db_Table_Abstract $table)
{
$this->table = $table;
$this->sql = $this->table->select();
}
/**
* Date au format AAAAMM
* @param string $date
* @param boolean $stock
*/
public function setDate($date, $stock = false)
{
$this->date = $date;
$this->dateStock = $stock;
}
public function setCode($name)
{
$this->code = $name;
}
public function setType($name)
{
}
public function getSqlRule()
{
$this->sql->from($this->table, array('COUNT(*) AS NB'));
$formatedDate = substr($this->date,0,4).'-'.substr($this->date,4,2);
if ($this->dateStock === true) {
$this->sql->where("dateSuppr!=0");
} else {
$this->sql->where("dateAjout BETWEEN '".$formatedDate."-01 00:00:00' AND '".$formatedDate."-31 23:59:59'");
}
$this->sql->where('idClient=?', $this->code);
return $this->sql;
}
}

View File

@ -0,0 +1,355 @@
<?php
/**
* Comptabilise la consommation
* Logs brutes :
* Aucun traitement, fournir la consomation avec date et heure
* Logs consommation :
* Dédoublonnage,
* Condition d'exclusion
* Croiser les tables pour avoir un libellé
*
* Mettre une date sur les règles pour suivre la facturation dans le temps
*
*/
class Scores_Conso_Logs
{
protected $login = array();
protected $date;
protected $item;
/**
* Standard count rules
* Format :
* ITEM NAME => array(
* 'params' => array of supplemental sql and where
* 'duplicate' => none, day, month, period (specified if this params must not change)
* )
* @var array
*/
protected $rules = array (
'identite' => array(),
'annonces' => array(),
'dirigeants' => array(),
'dirigeantsop' => array(),
'evenements' => array(),
'etablissements' => array(),
'liens' => array(
'duplicate' => 'none',
),
'competences' => array(),
'kbis' => array(// à correler avec la table des commandes - Non fonctionnel
'duplicate' => 'day',
),
'synthese' => array(),
'ratios' => array(),
'bilan' => array(
'duplicate' => 'none',
),
'indiscore' => array(),
'indiscore2' => array(),
'indiscore3' => array(),
'indiscorep' => array(),
'indiscore2p' => array(),
'indiscore3p' => array(),
'flux' => array(),
'liassexls' => array(
'duplicate' => 'none',
),
'rapport1' => array(),
'rapport2' => array(),
'rapport3' => array(),
'marques' => array(),
'banque' => array(),
'conventions' => array(),
'groupeinfos' => array(),
'groupesarbo' => array(),
'infosreg' => array(),
'rechcsv' => array(
'duplicate' => 'none',
),
'greffe_bilans' => array(
'params' => array(
"params != 'Liste'"
),
'group' => array('login', 'siren', 'page', 'params', 'raisonSociale', 'period'),
),
'greffe_actes' => array(
'params' => array(
"params != 'Liste'"
),
'group' => array('login', 'siren', 'page', 'params', 'raisonSociale', 'period'),
),
'greffe_statuts' => array(
'group' => array('login', 'siren', 'page', 'params', 'raisonSociale', 'period'),
),
'bourse' => array(),
'scorecsf' => array(),
'avis_situation' => array(),
'privileges' => array(),
'commandeAsso' => array(),
'privcumul' => array(),
'privdetail' => array(),
'uploadbilan' => array(),
'histobodacc' => array(),
'aviscredit' => array(),
'tva' => array(),
'sirenExiste' => array(),
'histobodacc' => array(),
'valo' => array(),
'rnvp' => array(),
);
/**
* @var Zend_Db_Table_Abstract
*/
protected $table;
/**
*
* @var Zend_Db_Select
*/
protected $sql;
/**
*
* @param Zend_Db_Table_Abstract $table
*/
public function __construct(Zend_Db_Table_Abstract $table)
{
$this->table = $table;
$this->sql = $this->table->select();
}
/**
* Array of login
* @param array $login
*/
public function setLogin($login)
{
$this->login = $login;
}
/**
* Date au format AAAAMM
* @param string $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Code de l'élément à compter
* @param string $item
*/
public function setItem($item)
{
$this->item = $item;
}
/**
* Retourne requete SQL avec les règles
* @return Zend_Db_Select
*/
public function getSqlRule($file = false)
{
$this->addSqlLogin();
$this->addSqlItem($file);
$this->addSqlDate();
return $this->sql;
}
/**
* Retourne requete SQL
* @return Zend_Db_Select
*/
public function getSql()
{
$this->addSqlLogin();
$this->addSqlDate();
$columns = array(
'LOWER(login) AS login', 'page', 'LPAD(siren, 9, 0) AS siren', 'LPAD(nic, 5, 0) AS nic',
'params', 'raisonSociale', 'cp', 'ville', 'dateHeure', new Zend_Db_Expr('"none" as nbDoublon'));
$this->sql->from($this->table, $columns);
return $this->sql;
}
/**
*
* @param unknown $name
* @param unknown $value
*/
public function setOption($name, $value)
{
if ( null === $this->item ) {
return new Zend_Exception('Item is not set !');
}
if ($name == 'duplicate') {
if ( !array_key_exists('duplicate', $this->rules[$this->item]) ) {
switch ( strtolower($value) ) {
case 'day':
case 'jour':
$this->rules[$this->item]['duplicate'] = 'day';
break;
case 'month':
case 'mois':
case 'period':
case 'periode':
$this->rules[$this->item]['duplicate'] = 'period';
break;
}
}
}
}
/**
*
*/
public function addSqlLogin()
{
$this->sql->where($this->table->info('name').".login IN ('".join("','", $this->login)."')");
}
public function addSqlDate()
{
$formatedDate = substr($this->date,0,4).'-'.substr($this->date,4,2);
$this->sql->where("dateHeure BETWEEN '".$formatedDate."-01 00:00:00' AND '".$formatedDate."-31 23:59:59'");
}
public function addSqlItem($file = false)
{
$rule = array();
if ( array_key_exists($this->item, $this->rules) ){
$rule = $this->rules[$this->item];
}
// --- Group to deduplicate
if ( array_key_exists('duplicate', $rule) ) {
switch($rule['duplicate']) {
case 'day':
if ($file === false ) {
$columns = array('COUNT(*) AS doublon', "DATE_FORMAT(dateHeure, '%Y%m%d') AS period");
} else {
$columns = array(
'LOWER('.$this->table->info('name').'.login) AS login',
'page',
'LPAD(siren, 9, 0) AS siren',
'LPAD(nic, 5, 0) AS nic',
'params',
'raisonSociale',
'cp',
'ville',
'dateHeure',
"DATE_FORMAT(dateHeure, '%Y%m%d') AS period",
'COUNT(*) AS nbDoublon'
);
}
$this->sql->from($this->table, $columns);
if ( array_key_exists('group', $rule) ) {
$this->sql->group($rule['group']);
} else {
$this->sql->group(array('login', 'siren', 'page', 'raisonSociale', 'period'));
}
break;
case 'period':
if ($file === false ) {
/*SELECT count(doublon) as NB FROM () test*/
$columns = array('COUNT(*) AS doublon', "DATE_FORMAT(dateHeure, '%Y%m') AS period");
} else {
$columns = array(
'LOWER('.$this->table->info('name').'.login) AS login',
'page',
'LPAD(siren, 9, 0) AS siren',
'LPAD(nic, 5, 0) AS nic',
'params',
'raisonSociale',
'cp',
'ville',
'dateHeure',
"DATE_FORMAT(dateHeure, '%Y%m') AS period",
'COUNT(*) AS nbDoublon'
);
}
$this->sql->from($this->table, $columns);
if ( array_key_exists('group', $rule) ) {
$this->sql->group($rule['group']);
} else {
$this->sql->group(array('login', 'siren', 'page', 'raisonSociale', 'period'));
}
break;
case 'none':
default:
if ($file === false ) {
$columns = array('dateHeure AS period');
} else {
$columns = array(
'LOWER('.$this->table->info('name').'.login) AS login',
'page',
'LPAD(siren, 9, 0) AS siren',
'LPAD(nic, 5, 0) AS nic',
'params',
'raisonSociale',
'cp',
'ville',
'dateHeure',
new Zend_Db_Expr('"none" as nbDoublon')
);
}
$this->sql->from($this->table, $columns);
break;
}
}
// --- No duplicate rules
if ( !array_key_exists('duplicate', $rule) || count($rule) == 0 ) {
if ($file === false ) {
$columns = array('dateHeure');
} else {
$columns = array(
'LOWER('.$this->table->info('name').'.login) AS login',
'page',
'LPAD(siren, 9, 0) AS siren',
'LPAD(nic, 5, 0) AS nic',
'params',
'raisonSociale',
'cp',
'ville',
'dateHeure',
new Zend_Db_Expr('"none" as nbDoublon')
);
}
$this->sql->from($this->table, $columns);
}
// --- Apply item parameters
if ( array_key_exists('params', $rule) && count($rule['params'])>0 ) {
foreach ( $rule['params'] as $param ) {
$this->sql->where($param);
}
}
if ($file === true) {
$this->sql->setIntegrityCheck(false)
->joinLeft('utilisateurs', 'utilisateurs.login='.$this->table->info('name').'.login', array('referenceParDefaut'), 'sdv1');
}
$this->sql->where('page=?', $this->item);
$this->sql->order('dateHeure ASC');
}
}

View File

@ -0,0 +1,165 @@
<?php
/**
* Comptabilise la consommation surveillances
*
*/
class Scores_Conso_Surveillances
{
protected $login = array();
protected $date;
protected $dateStock;
protected $item;
/**
* Standard count rules
* Format :
* ITEM NAME => array(
* 'params' => array of supplemental sql and where
* 'duplicate' => none, day, month, period (specified if this params must not change)
* )
* @var array
*/
protected $rules = array (
'annonces' => array(),
'insee' => array(),
'bilans' => array(),
'score' => array(),
'actes' => array(),
'dirigeants' => array(),
'paiements' => array(),
'liens' => array(),
'privileges' => array(),
);
/**
* @var Zend_Db_Table_Abstract
*/
protected $table;
/**
*
* @var Zend_Db_Select
*/
protected $sql;
/**
*
* @param Zend_Db_Table_Abstract $table
*/
public function __construct(Zend_Db_Table_Abstract $table)
{
$this->table = $table;
$this->sql = $this->table->select();
}
/**
* Array of login
* @param array $login
*/
public function setLogin($login)
{
$this->login = $login;
}
/**
* Date au format AAAAMM
* @param string $date
* @param boolean $stock
*/
public function setDate($date, $stock = false)
{
$this->date = $date;
$this->dateStock = $stock;
}
/**
* Code de l'élément à compter
* @param string $item
*/
public function setItem($item)
{
$this->item = $item;
}
/**
* Retourne la requete
* @return Zend_Db_Select
*/
public function getSqlRule()
{
$this->addSqlLogin();
$this->addSqlItem();
$this->addSqlDate();
return $this->sql;
}
/**
*
* @param unknown $name
* @param unknown $value
*/
public function setOption($name, $value)
{
if ( null === $this->item ) {
return new Zend_Exception('Item is not set !');
}
if ($name == 'duplicate') {
if ( !array_key_exists('duplicate', $this->rules[$this->item]) ) {
switch ( strtolower($value) ) {
case 'day':
case 'jour':
$this->rules[$this->item]['duplicate'] = 'day';
break;
case 'month':
case 'mois':
case 'period':
case 'periode':
$this->rules[$this->item]['duplicate'] = 'period';
break;
}
}
}
}
/**
*
*/
public function addSqlLogin()
{
$this->sql->where("login IN ('".join("','", $this->login)."')");
}
public function addSqlDate()
{
$formatedDate = substr($this->date,0,4).'-'.substr($this->date,4,2);
if ($this->dateStock === true) {
$this->sql->where("dateSuppr!=0");
} else {
$this->sql->where("dateAjout BETWEEN '".$formatedDate."-01 00:00:00' AND '".$formatedDate."-31 23:59:59'");
}
}
public function addSqlItem()
{
$this->sql->from($this->table, array('COUNT(*) AS NB'));
$rule = $this->rules[$this->item];
//Apply item parameters
/*if ( array_key_exists('params', $rule) && count($rule['params'])>0 ) {
foreach ( $rule['params'] as $param ) {
$this->sql->where($param);
}
}*/
$this->sql->where('source=?', $this->item);
$this->sql->order('dateAjout ASC');
}
}

View File

@ -0,0 +1,376 @@
<?php
class Scores_Courrier_Generate
{
protected $format = 'odt';
protected $path = '';
protected $info = null;
public function __construct($numCommande, $type)
{
$c = Zend_Registry::get('config');
$this->path = realpath($c->profil->path->data).'/courrier/';
$this->info = new stdClass();
$this->info->ref = $numCommande;
$this->info->refType = $type;
}
public function setInfosCommande()
{
$typeCommande = $this->info->refType;
$id = $this->info->ref;
if ($typeCommande == 'ac') {
$commande = new Application_Model_Sdv1GreffeCommandesAc();
$sql = $commande->select()->where('id = ?', $id);
$result = $commande->fetchRow($sql);
$typeDocument = 'actes';
$gM = new Application_Model_JoGreffesActes();
$sql = $gM->select()
->where('siren=?', $result->siren)
->where('num_depot=?', $result->depotNum)
->where('date_depot=?', $result->depotDate)
->where('num_acte=?', $result->acteNum)
->where('date_acte=?', $result->acteDate)
->where('type_acte=?', $result->acteType);
$document = $gM->fetchRow($sql);
$this->info->libDocument = $document->type_acte_libelle;
$this->info->dateDocument = $result->acteDate;
$this->info->dateDepot = $result->acteType;
} else if ($typeCommande == 'bi') {
$commande = new Application_Model_Sdv1GreffeCommandesBi();
$sql = $commande->select()->where('id = ?', $id);
$result = $commande->fetchRow($sql);
$typeDocument = 'bilans';
$gM = new Application_Model_JoGreffesBilans();
$sql = $gM->select()
->where('siren=?', $result->siren)
->where('date_cloture=?', $result->bilanCloture);
if ( $result->bilanType == 'sociaux' || $result->bilanType == '' ) {
$sql->where("(type_comptes='sociaux' OR type_comptes='')");
} else {
$sql->where('type_comptes=?', $result->bilanType);
}
$sql->order('dateInsert DESC')->order('num_depot DESC')->limit(1);
$document = $gM->fetchRow($sql);
$this->info->libDocument = '';
$this->info->dateDocument = $result->bilanCloture;
} else if ($typeCommande == 'kb') {
$commande = new Application_Model_Sdv1GreffeCommandesKb();
$sql = $commande->select()->where('id = ?', $id);
$result = $commande->fetchRow($sql);
$typeDocument = 'kbis';
if ($result->type == 'M') {
$this->info->type = 'MAIL';
}
}
//Assignation des variables
$this->info->siren = $result->siren;
$this->info->typeDocument = $typeDocument;
}
public function setInfosIdentite()
{
// @todo : How to include old framework
require_once 'Metier/insee/classMInsee.php';
$insee = new MInsee();
$reponse = $insee->getIdentiteEntreprise($this->info->siren);
$this->info->commune = $reponse['codeCommune'];
$this->info->dept = $reponse['Dept'];
$this->info->siret = $reponse['Siret'];
$this->info->numRC = $reponse['NumRC'];
//$info->siren = substr($siren, 0, 3).' '.substr($siren, 3, 3).' '.substr($siren, 6, 3);
$this->info->nom = htmlspecialchars_decode($reponse['Nom'], ENT_QUOTES);
$this->info->adresse = htmlspecialchars_decode($reponse['Adresse'], ENT_QUOTES).' ';
if (empty($reponse['Adresse2']) == false) {
$info->adresse .= $reponse['Adresse2'].' ';
}
$this->info->adresse .= "\n".$reponse['CP'].' '.$reponse['Ville'];
}
public function setInfosTribunal()
{
// Adresse du tribunal de commerce
// @todo : How to include old framework
require_once 'Metier/bodacc/classMBodacc.php';
$iBodacc = new MBodacc();
$reponse = $iBodacc->getTribunauxParCommune($this->info->dept.$this->info->commune);
$tribunalLib = $reponse[0]['triNom'];
if (preg_match('/(A|B|C|D)/i', $this->info->numRC)) {
$libTrib = ' RCS '.
preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i', '', $tribunalLib);
} else if (preg_match('/(P)/i', $this->info->numRC)) {
$libTrib = ' RSAC '.
preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i', '', $tribunalLib);
}
$this->info->tribunalCode = $reponse[0]['triCode'];
$this->info->libTrib = $libTrib;
$this->info->tribunal->Adr = strtoupper(preg_replace('/ +/',' ',
$reponse[0]['triAdrNum'].' '.
$reponse[0]['triAdrIndRep'].' '.
$reponse[0]['triAdrTypeVoie'].' '.
$reponse[0]['triAdrVoie']));
$this->info->tribunal->AdrComp = strtoupper($reponse[0]['triAdrComp']);
$this->info->tribunal->CP = $reponse[0]['triCP'];
$this->info->tribunal->Ville = strtoupper($reponse[0]['triVille']);
}
public function setTarifs()
{
$tarifs = new Application_Model_Sdv1GreffeTarifs();
$sql = $tarifs->select()->where('codeTribunal = ?', $this->info->tribunalCode)
->where('type = ?', $this->info->typeDocument)
->where('annee = ?', date('Y'));
$result = $tarifs->fetchAll($sql)->toArray();
if (count($result) == 0) {
echo 'Commande '.$this->info->ref.' - Pas de tarifs d&eacute;fini pour le tribunal '.
$this->info->tribunal->Nom.' ('.$this->info->tribunalCode.')';
exit;
}
$this->info->prix = number_format($result[0]['prix'], 2, ',', ' ');
$this->info->enveloppe = $result[0]['enveloppe'];
}
protected function setDestinataire()
{
// Destinataire
$this->info->destinataire = "REGISTRE DU COMMERCE - GREFFE\n".
$this->normaliseVoie(trim($this->info->tribunal->Adr))."\n".
$this->normaliseVoie($this->info->tribunal->AdrComp)."\n".
$this->info->tribunal->CP.' '.$this->info->tribunal->Ville."\n";
}
protected function setSujet()
{
// Type de document demandé (actes ou bilans pour l'instant)
// [un Kbis / l'état d'endettement / la copie de jugement de XXX en date du XXX]
if ($this->info->typeDocument == 'bilans') {
$this->info->sujet = 'une copie du bilan au '.
substr($this->info->dateDocument, 6, 2).'/'.
substr($this->info->dateDocument, 4, 2).'/'.
substr($this->info->dateDocument, 0, 4);
} else if ($this->info->typeDocument == 'actes') {
$this->info->sujet = 'une copie de l\'acte '.$this->info->libDocument;
$this->info->sujet .= ' en date du '.
substr($this->info->dateDocument, 6, 2).'/'.
substr($this->info->dateDocument, 4, 2).'/'.
substr($this->info->dateDocument, 0, 4);
} else if ($this->info->typeDocument == 'kbis') {
$this->info->sujet = 'un extrait RCS';
}
}
protected function setSociete()
{
// Societe
$this->info->societe = $this->info->nom."\n".'( '.$this->info->siren.$this->info->libTrib.' )'."\n";
$this->info->societe .= $this->normaliseVoie($this->info->adresse);
}
protected function setMontant()
{
// Piece jointe et montant
if ($this->info->enveloppe) {
$this->info->montant = 'Ci-joint une enveloppe timbrée ainsi qu\'un '.
'chèque d\'un montant de '.$this->info->prix.
' euros en règlement de cette commande.';
} else {
$this->info->montant = 'Ci-joint un chèque d\'un montant de '.$this->info->prix.
' euros en règlement de cette commande.';
}
}
public function computeOdt()
{
$config = array(
'ZIP_PROXY' => 'PhpZipProxy',
);
require_once 'Vendors/odtphp/library/odf.php';
$odf = new Odf(__DIR__.'/Model/modeleLettreGreffe.odt', $config);
$this->setInfosCommande();
$this->setInfosIdentite();
$this->setInfosTribunal();
$this->setTarifs();
$this->setDestinataire();
$this->setSujet();
$this->setSociete();
$this->setMontant();
$file = $this->info->siren.'-'.$this->info->ref.'.odt';
$odf->setVars('destinataire', $this->info->destinataire, true, 'UTF-8');
$odf->setVars('date', date('d/m/Y'), true, 'UTF-8');
$odf->setVars('ref', $this->info->ref, true, 'UTF-8');
$odf->setVars('sujet', $this->info->sujet, true, 'UTF-8');
$odf->setVars('societe', $this->info->societe, true, 'UTF-8');
$odf->setVars('montant', $this->info->montant, true, 'UTF-8');
if ($this->info->type == 'MAIL') {
$odf->setVars('bymail',"ou à votre convenance par mail à : support@scores-decisions.com", true, 'UTF-8');
}
$odf->saveToDisk($this->path.$file);
if (file_exists($this->path.$file) == true) {
header('Content-Transfer-Encoding: none');
header('Content-type: application/vnd.oasis.opendocument.text');
header('Content-Length: '.filesize($this->path.$file));
header('Content-MD5: '.base64_encode(md5_file($this->path.$file)));
header('Content-Disposition:attachment; filename="'.$file.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo file_get_contents($this->path.$file);
} else {
echo 'Erreur Génération du fichier';
}
}
public function computePdf()
{
$this->setInfosCommande();
$this->setInfosIdentite();
$this->setInfosTribunal();
$this->setTarifs();
$this->setDestinataire();
$this->setSujet();
$this->setSociete();
$this->setMontant();
// initiate PDF
$pdf = new Scores_Courrier_Pdf();
/*
* Définition des marges
* Left, Top et Right
* Dimension du logo d'entete :
**/
$pdf->SetMargins(25, 50, 25);
$border = 0;
// add a page
$pdf->AddPage();
$pdf->SetFont("times", "", 10);
//Position de départ
$pdf->SetY(50);
//Bloc Addresse destinataire
$largeur = 80;
$positionX = 105;
$pdf->MultiCell($largeur, 5, $this->info->destinataire, $border, 'L', 0, 1, $positionX);
//Bloc Lieu, date
$date = date('d/m/Y');
$txt = "Rambouillet, le $date";
$positionY = $pdf->GetY()+5;
$pdf->MultiCell($largeur, 5, $txt, $border, 'L', 0, 1, $positionX, $positionY);
//Bloc objet
$positionY = $pdf->GetY()+5;
$pdf->MultiCell(20, 5, "Objet:", $border, 'L', 0, 0, '', $positionY, true);
$pdf->MultiCell(0, 5, "Commande de document", $border, 'L', 0, 1, '', '', true);
//Bloc ref
$pdf->MultiCell(20, 5, "Réf.", $border, 'L', 0, 0, '', '', true);
$pdf->MultiCell(0, 5, $this->info->ref, $border, 'L', 0, 1, '', '', true);;
//Bloc titre
$positionY = $pdf->GetY()+5;
$pdf->MultiCell(0, 5, "Madame, Monsieur,", $border, 'L', 0, 1, '', $positionY, true);
//Type de document demandé (actes ou bilans pour l'instant)
//[un Kbis / l'état d'endettement / la copie de jugement de XXX en date du XXX ]
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, "Nous vous prions de nous faire parvenir $this->info->sujet concernant la société:", $border, 'L', 0, 1, '', $positionY, true);
//Bloc société
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, $this->info->societe, $border, 'L', 0, 1, '', $positionY, true);
//Bloc pièce jointe
$positionY = $pdf->GetY()+5;
$pdf->MultiCell(0, 5, $this->info->montant, $border, 'L', 0, 1, '', $positionY, true);
//Bloc intitulé adresse reception
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5,
"Veuillez nous renvoyer le(s) document(s) par retour à l'adresse suivante:",
$border, 'L', 0, 1, '', $positionY, true);
//Bloc adresse s&d
$positionY = '';
$pdf->MultiCell(0, 5,
"SCORES ET DECISIONS" . "\n" .
"19 rue Clairefontaine". "\n" .
"78120 RAMBOUILLET" . "\n"
, $border, 'L', 0, 1, '', $positionY, true);
if ($this->info->type == 'MAIL') {
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5,
"ou à votre convenance par mail à : support@scores-decisions.com",
$border, 'L', 0, 1, '', $positionY, true);
}
//Bloc formule politesse
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, "Dans l'attente de notre prochain échange, nous vous prions de recevoir, Madame, Monsieur, l'expression de nos plus sincères salutations.", $border, 'L', 0, 1, '', $positionY, true);
$file = $this->info->siren.'-'.$this->info->ref.'.pdf';
$pdf->Output($this->path.$file, 'F');
if(file_exists($path.$file))
{
$content_type = 'application/pdf';
header('Content-Transfer-Encoding: none');
header('Content-type: '.$content_type.'');
header('Content-Length: '.filesize($this->path.$file));
header('Content-MD5: '.base64_encode(md5_file($this->path.$file)));
header('Content-Disposition: attachment, filename="'.$file.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo file_get_contents($this->path.$file);
}
}
protected function normaliseVoie($txt)
{
$replace_pairs = array(
'BD ' => 'BOULEVARD ',
'BVD ' => 'BOULEVARD ',
'AV ' => 'AVENUE ',
'AVE ' => 'AVENUE ',
'PL ' => 'PLACE ',
'PLA ' => 'PLACE ',
'PLAC ' => 'PLACE ',
'ESP ' => 'ESP ',
'RTE ' => 'ROUTE ',
'ST ' => 'SAINT ',
'STE ' => 'SAINTE ',
'QU ' => 'QUAI '
);
return strtr($txt, $replace_pairs);
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,26 @@
<?php
require_once 'Vendors/tcpdf/tcpdf.php';
require_once 'Vendors/fpdi/fpdi.php';
class Scores_Courrier_Pdf extends FPDI {
/**
* "Remembers" the template id of the imported page
*/
var $_tplIdx;
/**
* include a background template for every page
*/
function Header() {
if (is_null($this->_tplIdx)) {
$file = __DIR__.'/Model/modele.pdf';
$this->setSourceFile($file);
$this->_tplIdx = $this->importPage(1);
}
$this->useTemplate($this->_tplIdx);
}
function Footer() {
}
}

View File

@ -0,0 +1,87 @@
<?php
/**
* Miscellaneous functions to clean string.
*/
class Scores_Locale_String
{
/**
* Clean up a string value.
*
* Resulting string contains only alphanumerics and separators.
*
* @param $string
* A string to clean.
* @param $clean_slash
* Whether to clean slashes from the given string.
* @return
* The cleaned string.
*/
public static function cleanstring($string)
{
$transliterate = TRUE;
$reduce_ascii = FALSE;
$output = $string;
// Remove accents and transliterate
if ($transliterate) {
static $i18n_loaded = false;
static $translations = array();
if (!$i18n_loaded) {
$path = realpath(dirname(__FILE__));
if (is_file($path .'/i18n-ascii.txt')) {
$translations = parse_ini_file($path .'/String/i18n-ascii.txt');
}
$i18n_loaded = true;
}
$output = strtr($output, $translations);
}
// Reduce to the subset of ASCII96 letters and numbers
if ($reduce_ascii) {
$pattern = '/[^a-zA-Z0-9\/]+/ ';
$output = preg_replace($pattern, $separator, $output);
}
return $output;
}
public static function cleanutf8($string)
{
$transliterate = TRUE;
$output = $string;
// Remove accents and transliterate
if ($transliterate) {
static $i18n_loaded = false;
static $translations = array();
if (!$i18n_loaded) {
$path = realpath(dirname(__FILE__));
if (is_file($path .'/i18n-ascii.txt')) {
$translations = parse_ini_file($path .'/String/i18n-ascii.txt');
}
$i18n_loaded = true;
}
$output = strtr($output, $translations);
}
return $output;
}
// Fixes the encoding to uf8
public static function fixEncoding($in_str)
{
$cur_encoding = mb_detect_encoding($in_str) ;
if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8"))
return $in_str;
else
return utf8_encode($in_str);
} // fixEncoding
public static function cleanstring_deep($value)
{
$value = is_array($value) ?
array_map('self::cleanstring_deep', $value) :
cleanstring($value);
return $value;
}
}

View File

@ -0,0 +1,564 @@
; global transliteration
[default]
À = "A"
Á = "A"
 = "A"
à = "A"
Ä = "Ae"
Å = "A"
Æ = "A"
Ā = "A"
Ą = "A"
Ă = "A"
Ç = "C"
Ć = "C"
Č = "C"
Ĉ = "C"
Ċ = "C"
Ď = "D"
Đ = "D"
È = "E"
É = "E"
Ê = "E"
Ë = "E"
Ē = "E"
Ę = "E"
Ě = "E"
Ĕ = "E"
Ė = "E"
Ĝ = "G"
Ğ = "G"
Ġ = "G"
Ģ = "G"
Ĥ = "H"
Ħ = "H"
Ì = "I"
Í = "I"
Î = "I"
Ï = "I"
Ī = "I"
Ĩ = "I"
Ĭ = "I"
Į = "I"
İ = "I"
IJ = "IJ"
Ĵ = "J"
Ķ = "K"
Ľ = "K"
Ĺ = "K"
Ļ = "K"
Ŀ = "K"
Ł = "L"
Ñ = "N"
Ń = "N"
Ň = "N"
Ņ = "N"
Ŋ = "N"
Ò = "O"
Ó = "O"
Ô = "O"
Õ = "O"
Ö = "Oe"
Ø = "O"
Ō = "O"
Ő = "O"
Ŏ = "O"
Œ = "OE"
Ŕ = "R"
Ř = "R"
Ŗ = "R"
Ś = "S"
Ş = "S"
Ŝ = "S"
Ș = "S"
Š = "S"
Ť = "T"
Ţ = "T"
Ŧ = "T"
Ț = "T"
Ù = "U"
Ú = "U"
Û = "U"
Ü = "Ue"
Ū = "U"
Ů = "U"
Ű = "U"
Ŭ = "U"
Ũ = "U"
Ų = "U"
Ŵ = "W"
Ŷ = "Y"
Ÿ = "Y"
Ý = "Y"
Ź = "Z"
Ż = "Z"
Ž = "Z"
à = "a"
á = "a"
â = "a"
ã = "a"
ä = "ae"
ā = "a"
ą = "a"
ă = "a"
å = "a"
æ = "ae"
ç = "c"
ć = "c"
č = "c"
ĉ = "c"
ċ = "c"
ď = "d"
đ = "d"
è = "e"
é = "e"
ê = "e"
ë = "e"
ē = "e"
ę = "e"
ě = "e"
ĕ = "e"
ė = "e"
ƒ = "f"
ĝ = "g"
ğ = "g"
ġ = "g"
ģ = "g"
ĥ = "h"
ħ = "h"
ì = "i"
í = "i"
î = "i"
ï = "i"
ī = "i"
ĩ = "i"
ĭ = "i"
į = "i"
ı = "i"
ij = "ij"
ĵ = "j"
ķ = "k"
ĸ = "k"
ł = "l"
ľ = "l"
ĺ = "l"
ļ = "l"
ŀ = "l"
ñ = "n"
ń = "n"
ň = "n"
ņ = "n"
ʼn = "n"
ŋ = "n"
ò = "o"
ó = "o"
ô = "o"
õ = "o"
ö = "oe"
ø = "o"
ō = "o"
ő = "o"
ŏ = "o"
œ = "oe"
ŕ = "r"
ř = "r"
ŗ = "r"
ś = "s"
š = "s"
ş = "s"
ť = "t"
ţ = "t"
ù = "u"
ú = "u"
û = "u"
ü = "ue"
ū = "u"
ů = "u"
ű = "u"
ŭ = "u"
ũ = "u"
ų = "u"
ŵ = "w"
ÿ = "y"
ý = "y"
ŷ = "y"
ż = "z"
ź = "z"
ž = "z"
ß = "ss"
ſ = "ss"
Α = "A"
Ά = "A"
Ἀ = "A"
Ἁ = "A"
Ἂ = "A"
Ἃ = "A"
Ἄ = "A"
Ἅ = "A"
Ἆ = "A"
Ἇ = "A"
ᾈ = "A"
ᾉ = "A"
ᾊ = "A"
ᾋ = "A"
ᾌ = "A"
ᾍ = "A"
ᾎ = "A"
ᾏ = "A"
Ᾰ = "A"
Ᾱ = "A"
Ὰ = "A"
Ά = "A"
ᾼ = "A"
Β = "B"
Γ = "G"
Δ = "D"
Ε = "E"
Έ = "E"
Ἐ = "E"
Ἑ = "E"
Ἒ = "E"
Ἓ = "E"
Ἔ = "E"
Ἕ = "E"
Έ = "E"
Ὲ = "E"
Ζ = "Z"
Η = "I"
Ή = "I"
Ἠ = "I"
Ἡ = "I"
Ἢ = "I"
Ἣ = "I"
Ἤ = "I"
Ἥ = "I"
Ἦ = "I"
Ἧ = "I"
ᾘ = "I"
ᾙ = "I"
ᾚ = "I"
ᾛ = "I"
ᾜ = "I"
ᾝ = "I"
ᾞ = "I"
ᾟ = "I"
Ὴ = "I"
Ή = "I"
ῌ = "I"
Θ = "TH"
Ι = "I"
Ί = "I"
Ϊ = "I"
Ἰ = "I"
Ἱ = "I"
Ἲ = "I"
Ἳ = "I"
Ἴ = "I"
Ἵ = "I"
Ἶ = "I"
Ἷ = "I"
Ῐ = "I"
Ῑ = "I"
Ὶ = "I"
Ί = "I"
Κ = "K"
Λ = "L"
Μ = "M"
Ν = "N"
Ξ = "KS"
Ο = "O"
Ό = "O"
Ὀ = "O"
Ὁ = "O"
Ὂ = "O"
Ὃ = "O"
Ὄ = "O"
Ὅ = "O"
Ὸ = "O"
Ό = "O"
Π = "P"
Ρ = "R"
Ῥ = "R"
Σ = "S"
Τ = "T"
Υ = "Y"
Ύ = "Y"
Ϋ = "Y"
Ὑ = "Y"
Ὓ = "Y"
Ὕ = "Y"
Ὗ = "Y"
Ῠ = "Y"
Ῡ = "Y"
Ὺ = "Y"
Ύ = "Y"
Φ = "F"
Χ = "X"
Ψ = "PS"
Ω = "O"
Ώ = "O"
Ὠ = "O"
Ὡ = "O"
Ὢ = "O"
Ὣ = "O"
Ὤ = "O"
Ὥ = "O"
Ὦ = "O"
Ὧ = "O"
ᾨ = "O"
ᾩ = "O"
ᾪ = "O"
ᾫ = "O"
ᾬ = "O"
ᾭ = "O"
ᾮ = "O"
ᾯ = "O"
Ὼ = "O"
Ώ = "O"
ῼ = "O"
α = "a"
ά = "a"
ἀ = "a"
ἁ = "a"
ἂ = "a"
ἃ = "a"
ἄ = "a"
ἅ = "a"
ἆ = "a"
ἇ = "a"
ᾀ = "a"
ᾁ = "a"
ᾂ = "a"
ᾃ = "a"
ᾄ = "a"
ᾅ = "a"
ᾆ = "a"
ᾇ = "a"
ὰ = "a"
ά = "a"
ᾰ = "a"
ᾱ = "a"
ᾲ = "a"
ᾳ = "a"
ᾴ = "a"
ᾶ = "a"
ᾷ = "a"
β = "b"
γ = "g"
δ = "d"
ε = "e"
έ = "e"
ἐ = "e"
ἑ = "e"
ἒ = "e"
ἓ = "e"
ἔ = "e"
ἕ = "e"
ὲ = "e"
έ = "e"
ζ = "z"
η = "i"
ή = "i"
ἠ = "i"
ἡ = "i"
ἢ = "i"
ἣ = "i"
ἤ = "i"
ἥ = "i"
ἦ = "i"
ἧ = "i"
ᾐ = "i"
ᾑ = "i"
ᾒ = "i"
ᾓ = "i"
ᾔ = "i"
ᾕ = "i"
ᾖ = "i"
ᾗ = "i"
ὴ = "i"
ή = "i"
ῂ = "i"
ῃ = "i"
ῄ = "i"
ῆ = "i"
ῇ = "i"
θ = "th"
ι = "i"
ί = "i"
ϊ = "i"
ΐ = "i"
ἰ = "i"
ἱ = "i"
ἲ = "i"
ἳ = "i"
ἴ = "i"
ἵ = "i"
ἶ = "i"
ἷ = "i"
ὶ = "i"
ί = "i"
ῐ = "i"
ῑ = "i"
ῒ = "i"
ΐ = "i"
ῖ = "i"
ῗ = "i"
κ = "k"
λ = "l"
μ = "m"
ν = "n"
ξ = "ks"
ο = "o"
ό = "o"
ὀ = "o"
ὁ = "o"
ὂ = "o"
ὃ = "o"
ὄ = "o"
ὅ = "o"
ὸ = "o"
ό = "o"
π = "p"
ρ = "r"
ῤ = "r"
ῥ = "r"
σ = "s"
ς = "s"
τ = "t"
υ = "y"
ύ = "y"
ϋ = "y"
ΰ = "y"
ὐ = "y"
ὑ = "y"
ὒ = "y"
ὓ = "y"
ὔ = "y"
ὕ = "y"
ὖ = "y"
ὗ = "y"
ὺ = "y"
ύ = "y"
ῠ = "y"
ῡ = "y"
ῢ = "y"
ΰ = "y"
ῦ = "y"
ῧ = "y"
φ = "f"
χ = "x"
ψ = "ps"
ω = "o"
ώ = "o"
ὠ = "o"
ὡ = "o"
ὢ = "o"
ὣ = "o"
ὤ = "o"
ὥ = "o"
ὦ = "o"
ὧ = "o"
ᾠ = "o"
ᾡ = "o"
ᾢ = "o"
ᾣ = "o"
ᾤ = "o"
ᾥ = "o"
ᾦ = "o"
ᾧ = "o"
ὼ = "o"
ώ = "o"
ῲ = "o"
ῳ = "o"
ῴ = "o"
ῶ = "o"
ῷ = "o"
¨ = ""
΅ = ""
᾿ = ""
= ""
῍ = ""
῝ = ""
῎ = ""
῞ = ""
῏ = ""
῟ = ""
= ""
῁ = ""
΄ = ""
΅ = ""
= ""
῭ = ""
ͺ = ""
= ""
А = "A"
Б = "B"
В = "V"
Г = "G"
Д = "D"
Е = "E"
Ё = "E"
Ж = "ZH"
З = "Z"
И = "I"
Й = "I"
К = "K"
Л = "L"
М = "M"
Н = "N"
О = "O"
П = "P"
Р = "R"
С = "S"
Т = "T"
У = "U"
Ф = "F"
Х = "KH"
Ц = "TS"
Ч = "CH"
Ш = "SH"
Щ = "SHCH"
Ы = "Y"
Э = "E"
Ю = "YU"
Я = "YA"
а = "A"
б = "B"
в = "V"
г = "G"
д = "D"
е = "E"
ё = "E"
ж = "ZH"
з = "Z"
и = "I"
й = "I"
к = "K"
л = "L"
м = "M"
н = "N"
о = "O"
п = "P"
р = "R"
с = "S"
т = "T"
у = "U"
ф = "F"
х = "KH"
ц = "TS"
ч = "CH"
ш = "SH"
щ = "SHCH"
ы = "Y"
э = "E"
ю = "YU"
я = "YA"
Ъ = ""
ъ = ""
Ь = ""
ь = ""
ð = "d"
Ð = "D"
þ = "th"
Þ = "TH"

View File

@ -0,0 +1,2 @@
[default]
№ = "N°"

View File

@ -0,0 +1,130 @@
<?php
class Scores_Mail_Method extends Zend_Mail
{
protected $config;
protected $transport;
/**
* Gestion de l'envoi des mails en fonction de la configuration
* Fournir un objet de configuration ou utiliser la configuration de l'application
* method => smtp, sendmail, file
* Si method = smtp
* (host => IP, dns)
*
* Activer l'authentification
* (auth => login, plain, ....)
* (username => )
* (password => )
*/
public function __construct( $config = null )
{
if ($config === null) {
$c = Zend_Registry::get('config');
$this->config = $c->profil->mail;
} else {
$this->config = $config;
}
$this->_charset = 'ISO-8859-15';
// --- Configuration du transport SMTP
if ( $this->config->method == 'smtp' ) {
$config = array();
if ( isset($this->config->auth) ) {
$config['auth'] = $this->config->auth;
if ( isset($this->config->username) ) {
$config['username'] = $this->config->username;
}
if ( isset($this->config->password) ) {
$config['password'] = $this->config->password;
}
}
if ( isset($this->config->port) ) {
$config['port'] = $this->config->port;
}
$tr = new Zend_Mail_Transport_Smtp($this->config->host, $config);
}
// --- Configuration transport Sendmail
if ( $this->config->method == 'sendmail' ) {
$tr = new Zend_Mail_Transport_Sendmail();
}
// --- Configuration transport File
if ( $this->config->method == 'file' ) {
$tr = new Zend_Mail_Transport_File(array('callback' => array($this, 'recipientFilename')));
}
$this->transport = $tr;
}
/**
* Champ From en fonction de la clé de configuration
* @param string $configKey
*/
public function setFromKey($configKey)
{
$email = $this->config->email->$configKey;
$this->setFrom($email, ucfirst($configKey));
}
/**
* Champ To en fonction de la clé de configuration
* @param string $configKey
*/
public function addToKey($configKey)
{
$email = $this->config->email->$configKey;
$this->addTo($email, ucfirst($configKey));
}
/**
* Définit le sujet de l'email
* @param string $texte
*/
public function setSubjectC($texte = '')
{
$this->setSubject($this->txtConvert($texte));
}
/**
* Définit le corps de l'email au format texte
* @param string $texte
*/
public function setBodyTextC($texte = '')
{
$this->setBodyText($this->txtConvert($texte));
}
/**
* Définit le corps de l'email au format html
* @param string $html
*/
public function setBodyHtmlC($html = '')
{
$this->setBodyHtml($this->txtConvert($html));
}
/**
* Envoi de l'emai
*/
public function execute()
{
return $this->send($this->transport);
}
//We suppose that character encoding of strings is UTF-8 on PHP script.
protected function txtConvert($string)
{
return mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');
}
protected function recipientFilename($transport)
{
return $transport->recipients . '_' . mt_rand() . '.tmp';
}
}

237
library/Scores/Stat/Op.php Normal file
View File

@ -0,0 +1,237 @@
<?php
class Scores_Stat_Op
{
protected $sql = array(
'bod' => array(
array(
'table' => 'jo.bodacc_detail',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'annonce' => array(
array(
'table' => 'jo.annonces',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSaisie={id}',
'source IN ("JS","TS","GC","PC") AND (dateInsert BETWEEN "{begin}" AND "{end}" OR dateUpdate BETWEEN "{begin}" AND "{end}")',
),
'group' => array(),
'order' => array(),
),
),
'asso' => array(
array(
'table' => 'jo.asso',
'columnsTotal' => array('COUNT(*) as Nb'),
'columnsCsv' => array('*'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
)
),
'dir' => array(
array(
'table' => 'jo.rncs_dirigeants',
'columnsTotal' => array('COUNT(*) as Nb'),
'columnsCsv' => array('*'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'cac' => array(
array(
'table' => 'jo.bodacc_dirigeants',
'columnsTotal' => array('COUNT(*) as Nb'),
'columnsCsv' => array('*'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'boamp' => array(
array(
'table' => 'jo.boamp_lots',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
array(
'table' => 'jo.boamp_detail',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'client' => array(
array(
'table' => 'jo.sirenage_clients',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'marque' => array(
array(
'table' => 'bopi.marques',
'columnsTotal' => array('COUNT(*) as Nb'),
'columnsCsv' => array('*'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'lien' => array(
array(
'table' => 'jo.liens2',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idInsert={id} AND dateInsert BETWEEN "{begin}" AND "{end}" OR
idUpdate={id} AND dateUpdate BETWEEN "{begin}" AND "{end}" OR
idSuppr={id} AND dateSuppr BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
array(
'table' => 'jo.liensRef',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idInsert={id} AND dateInsert BETWEEN "{begin}" AND "{end}" OR
idUpdate={id} AND dateUpdate BETWEEN "{begin}" AND "{end}" OR
idSuppr={id} AND dateSuppr BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
array(
'table' => 'jo.liensDoc',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idInsert={id}',
'dateInsert BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'bilansaisie' => array(
array(
'table' => 'jo.bilans_user',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idUtilisateur={id} AND dateAction BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
'tourisme' => array(
array(
'table' => 'jo.tourisme',
'columnsTotal' => array('COUNT(*) as Nb'),
'where' => array(
'idSirenage={id}',
'dateUpdate BETWEEN "{begin}" AND "{end}"',
),
'group' => array(),
'order' => array(),
),
),
);
protected $category;
protected $user;
protected $begin;
protected $end;
protected $db;
public function __construct($category, $user, $dateBegin, $dateEnd = null)
{
$this->category = $category;
$this->user = $user;
$this->begin = $dateBegin.' 00:00:00';
$this->end = $dateBegin.' 23:59:59';
if ($dateEnd !== null) {
$this->end = $dateEnd.' 23:59:59';
}
$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
}
public function total()
{
$config = $this->sql[$this->category];
$nb = 0;
foreach ($config as $param) {
$sql = $this->db->select()->from($param['table'], $param['columnsTotal']);
foreach ($param['where'] as $where) {
$where = preg_replace('/\{id\}/', $this->user, $where);
$where = preg_replace('/\{begin\}/', $this->begin, $where);
$where = preg_replace('/\{end\}/', $this->end, $where);
$sql->where($where);
}
$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
$result = $this->db->fetchRow($sql);
if ($result !== null) {
$nb = $nb + $result->Nb;
}
}
return $nb;
}
public function csv()
{
$config = $this->sql[$this->category];
foreach ($config as $param) {
$sql = $this->db->select()->from($param['table'], $param['columnsCSV']);
foreach ($param['where'] as $where) {
$where = preg_replace('/\{id\}/', $this->user, $where);
$where = preg_replace('/\{begin\}/', $this->begin, $where);
$where = preg_replace('/\{end\}/', $this->end, $where);
$sql->where($where);
}
$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
$result = $this->db->fetchRow($sql);
if ($result !== null) {
}
}
}
}

View File

@ -0,0 +1,92 @@
<?php
require_once 'Metier/insee/classMInsee.php';
/**
*
* @author mricois
*
*/
class Scores_Surveillance_File
{
/**
* Declare the header
* @var array
*/
protected $header = array(
'siren',
'nic',
'ref',
'login',
'email',
'source',
);
protected $headerRequired = array(
'siren',
'nic',
'ref',
);
protected $position = array();
protected $delimiter = ',';
/**
*
* @param string $delimiter
*/
public function __construct($delimiter = null)
{
$this->delimiter = ',';
if (null !== $delimiter) {
$this->delimiter = $delimiter;
}
}
/**
* Check file header
* @param string $file
* @return boolean|array
*/
public function checkHeader($file)
{
$row = 0;
$error = array();
if (($handle = fopen($file, 'r')) !== false) {
while (($data = fgetcsv($handle, 0, $this->delimiter, '"')) !== false) {
$num = count($data);
//First line
if ($row == 0) {
//Detect key
foreach ( $this->header as $key ) {
for ( $c=0; $c < $num; $c++ ) {
if ( $key == strtolower($data[$c]) ) {
$this->position[$key] = $c;
}
}
}
break;
}
$row++;
}
fclose($handle);
}
if ( count($this->position) > 0 ) {
$tabKey = array_keys($this->position);
foreach( $this->headerRequired as $key) {
if ( !in_array($key, $tabKey) ) {
return false;
}
}
return $tabKey;
}
return false;
}
public function setCmd(){}
public function loadLines(){}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,614 @@
<?php
class Scores_Validate_IpInNetwork extends Zend_Validate_Ip
{
const NOT_IN_NETWORK = 'notInNetwork';
const LOW_IN_NETWORK = 'lowInNetwork';
const HIGH_IN_NETWORK = 'highInNetwork';
const INVALID_NETWORK = 'invalidNetwork';
const MISSING_NETWORK = 'missingNetwork';
/**
* A CIDR number (valid values 0-32)
* @var int
*/
protected $_cidr = 0;
/**
* A decimal 32-bit netmask
* @var string
*/
protected $_netmask = '255.255.255.255';
/**
* A 4-octet IPv4 network address
* @var string
*/
protected $_network = null;
/**
* A network/mask notation or network range
* @var string
*/
protected $_notation = null;
/**
* Unsigned decimal "from" IP address
* @var string
*/
protected $_rangeFrom = null;
/**
* Unsigned decimal "to" IP address
* @var string
*/
protected $_rangeTo = 0;
/**
* Will throw Exception instead of trigger_error if true
* @var false
*/
protected $_throw = false;
/**
* Constructor for IpInNetwork class
*
* @desc <p>Accepts an array with options. Also adds the error messages to the parent's message templates.</p>
* @example <p>List of allow options and their use:
* $options argument must be an array and allows two key/value pairs for this class and passes on any remaining
* values to the parent class Zend_Validate_Ip. If key 'network' exists it will pass on the value to method
* setNetworkNotation and for key 'throw' to setThrow4Notation.</p>
* @see Zend_Validate_Ip::__construct()
* @see Scores_Validate_IpInNetwork::setNetworkNotation()
* @see Scores_Validate_IpInNetwork::setThrow4Notation()
* @param array $options
* @return void
*/
public function __construct($options = array()) {
if ( !empty($options) && is_array($options) ) {
if ( array_key_exists('throw',$options) ) {
$this->setThrow4Notation($options['throw']);
unset($options['throw']);
}
if ( array_key_exists('network',$options) ) {
$this->setNetworkNotation($options['network']);
unset($options['network']);
}
}
$this->setMessages(array());
parent::__construct($options);
}
/**
* (non-PHPdoc)
* @see Zend_Validate_Abstract::setMessages()
*/
public function setMessages(array $messages) {
$newMessages = array(
self::MISSING_NETWORK => 'No valid network has been given to validate against',
self::INVALID_NETWORK => 'The network is not an accepted format',
self::NOT_IN_NETWORK => "The ip '%value%' does not match the provided 32 network",
self::LOW_IN_NETWORK => "The ip '%value%' is lower in range than the provided network",
self::HIGH_IN_NETWORK => "The ip '%value%' is higher in range than the provided network",
);
foreach ( $newMessages as $messageKey => $messageString ) {
if ( !isset($this->_messageTemplates[$messageKey]) ) {
$this->_messageTemplates[$messageKey] = $messageString;
} elseif ( !empty($messages) && array_key_exists($messageKey,$messages) ) {
$this->_messageTemplates[$messageKey] = $messages[$messageKey];
unset($messages[$messageKey]);
}
}
empty($messages) || parent::setMessages($messages) ;
return $this;
}
/**
* (non-PHPdoc)
* @see Zend_Validate_Ip::isValid()
*/
public function isValid($value) {
if ( true === parent::isValid($value) ) {
$notation = $this->_getNotation();
if ( !empty($notation) ) {
// a valid notation has been set
$network = $this->_getNetwork();
if ( !empty($network) ) {
if ( true === $this->_validateIpInNetwork($value) ) {
return true;
}
} else {
if ( true === $this->_validateIpInRange($value) ) {
return true;
}
}
// NOTE: Errors are only available in regards to the value (ip address) and not the network/netmask (notation)
$errors = $this->getErrors();
if ( empty($errors) ) {
$this->_error(self::NOT_IN_NETWORK);
}
} else {
$this->_error(self::MISSING_NETWORK);
}
}
return false;
}
/**
* Validates the IP in a given network
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 16:34:00 CST
* @author aw
* @desc <p>Takes the CIDR and network (IP) address and validates the given IP address against it. Sets the appropriate
* errors if the IP is not a match for the network.</p>
* @param string $ip
* @return bool
*/
protected function _validateIpInNetwork($ip) {
$netmask = $this->getCidr();
$network = $this->_getNetwork();
// lets get this out of the way first
if ( 32 === $netmask ) {
// this network has to match the IP
if ( $network === $ip ) {
return true;
} else {
$this->_error(self::NOT_IN_NETWORK);
return false;
}
}
// get the unsigned integers for the IP and network address
$ip_addr_uDec = $this->_makeUnsignedAddress($ip);
$lNetwork_uDec = $this->_makeUnsignedAddress($network);
// let verify the IP against the lower end of the range
if ( $ip_addr_uDec < $lNetwork_uDec ) {
// the ip is below the network range
$this->_error(self::LOW_IN_NETWORK);
return false;
}
// well then, finally verify the IP against the uppoer end of the range
// add the decimal representation of the netmask to the network IP
$netmask_uDec1 = $netmask < 31 ? pow(2, (32-$netmask)) - 1 : 1 ;
$netmask_uDec = pow(2, 32-$netmask) - 1 ;
$uNetwork_uDec = $lNetwork_uDec + $netmask_uDec;
if ( $ip_addr_uDec > $uNetwork_uDec ) {
// the ip is above the network range
$this->_error(self::HIGH_IN_NETWORK);
return false;
}
return true;
}
/**
* Validates the IP in a given range
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/16 13:06:00 CST
* @author aw
* @desc <p>Takes the "from" and "to" (IP) address and validates the given IP address against it. Sets the appropriate
* errors if the IP is not within the defined range.</p>
* @param string $ip
* @return bool
*/
protected function _validateIpInRange($ip) {
$uInt_Ip = $this->_makeUnsignedAddress($ip);
if ( is_numeric($this->_rangeFrom) && $uInt_Ip >= $this->_rangeFrom ) {
if ( $uInt_Ip <= $this->_rangeTo ) {
return true;
} elseif ( is_numeric($this->_rangeTo) ) {
$this->_error(self::HIGH_IN_NETWORK);
return false;
}
} elseif ( is_numeric($this->_rangeFrom) ) {
$this->_error(self::LOW_IN_NETWORK);
return false;
}
$this->_error(self::MISSING_NETWORK);
return false;
}
/**
* Set the network (notation) to the properties
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 13:43:00 CST
* @author aw
* @desc <p>The network is usually a notation with a network/netmask combination. The method uses two methods to validate
* the netmask and the network address. If the notation is a range fromIPAddress-toIPAddress the netmask and network address
* are ignored. The isValid() will then attempt to validate the value within the range and not the network segment.</p>
* string $notation network/address (128.0.0.0/24) (128.0.0.0/255.255.255.0) or (128.0.0.0-128.0.0.255)
* @return object|false Awd_Validate_IpInNetwork
*/
public function setNetworkNotation($notation) {
$network = false !== strpos($notation, '/') ? $this->_evaluateNetmask($notation) : false ;
if ( false !== $network) {
// a valid CIDR/netmask has been found
if ( true === parent::isValid($network) ) {
if ( $this->_validateNetwork($network) ) {
$this->_network = $network;
$this->_notation = $notation;
return $this;
}
} else {
$this->_invalidNetwork(__LINE__);
}
} elseif ( false !== strpos($notation, '-') ) {
// the notation is looking like a from-to IP range
if ( true === $this->_validateRange($notation) ) {
$this->_notation = $notation;
return $this;
}
}
return false;
}
/**
* Sets the value for _throw property
*
* @since Version 0.1.36
* @version 0.1.35 2012/01/17 08:23:00 CST
* @author aw
* @desc <p>The value determines if the application will throw an exception or trigger an E_USER_WARNING if
* an error was found in the submitted network notation. The default is false.</p>
* @throws E_USER_WARNING if the argument is not of type bool
* bool $throw
* @return object Awd_Validate_IpInNetwork
*/
public function setThrow4Notation($throw = false) {
if ( !is_bool($throw) ) {
$msg = '[AWD] Programming error: The argument is not a boolean value';
trigger_error($msg,E_USER_WARNING);
}
$this->_throw = $throw;
return $this;
}
/**
* Gets the value for _throw property
*
* @since Version 0.1.36
* @version 0.1.35 2012/01/17 08:27:00 CST
* @author aw
* @desc <p>The value determines if the application will throw an exception or trigger an E_USER_WARNING if
* an error was found in the submitted network notation. The default is false.</p>
* @return bool
*/
public function getThrow4Notation() {
return (bool) $this->_throw;
}
/**
* Gets the network (notation) as it has been set if valid
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 16:08:00 CST
* @author aw
* @desc <p>If empty the network (notation) was either not set or not valid. Hence, this method can be used to
* verify if setting a network range or notation was successful with the constructor.</p>
* @return string
*/
public function getNetworkNotation() {
return (string) $this->_getNotation();
}
/**
* Protected method to gets the network (notation) as it has been set if valid
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 16:08:00 CST
* @author aw
* @desc <p>Note that the notation is only available when it passed the internal validation. Internally (protected)
* the network represents the network (IP) address whereas the notation is the full string as set when is valid.
* The notation is a representation of network range or network/mask. This method essentially returns internally
* (protected) the same result as the public method getNetworkNotation().</p>
* @return string|null
*/
protected function _getNotation() {
return empty($this->_notation) ? null : (string) $this->_notation ;
}
/**
* Gets the network address from the notation if a valid address and mask has been set
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 16:18:00 CST
* @author aw
* @desc <p>Note that internally (protected) the network represents the network (IP) address extracted from the
* "network notation", i.e. a representation of network range or network/mask. If the notation was not valid or a
* network range has been set this value will be empty.</p>
* @return string
*/
protected function _getNetwork() {
return (string) $this->_network;
}
/**
* Gets the CIDR from the notation if a valid address and mask has been set
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/14 16:26:00 CST
* @author aw
* @desc <p>The CIDR has been extracted from the "network notation", i.e. a representation of network/mask or
* network/CIDR. If the notation was not valid or a network range has been set this value will be empty.</p>
* @return int
*/
public function getCidr() {
return (int) $this->_cidr;
}
/**
* Evaluates the netmask from a notation
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/15 10:12:00 CST
* @author aw
* @desc <p>The notation is usually set as a {network/CIDR} or {network/netmask} notation. This method examines
* the string following a slash. A CIDR mask will be verified for its number whereas a netmask is passed to
* another method _validateNetmask() for validation and if valid converted into a CIDR representation. In
* either case if the value is valid the remaining network (IP) address is returned or false on failure.</p>
* @throws Calls method _invalidNetwork() when a failure is detected
* @param string $notation
* @return string|bool (false)
*/
protected function _evaluateNetmask($notation) {
// split the notation in network and netmask information
list($network, $netmask) = explode('/', $notation, 2);
if ( is_numeric($netmask) ) {
// does look like a CIDR netmask
$between = new Zend_Validate_Between(array('min'=>1,'max'=>32));
if ( true === $between->isValid($netmask) ) {
$this->_cidr = (int) $netmask;
return $network;
} else {
$error_msgs = $between->getMessages();
if ( !empty($error_msgs) && is_array($error_msgs) ) {
$msg = array_shift($error_msgs);
} else {
// fallback, should not really be an option
$msg = sprintf('The netmask [ %s ] is not a valid option',$netmask);
}
// oops, this CIDR is not a valid range
return $this->_invalidNetwork(__LINE__.' - '.$msg);
}
} elseif ( !empty($netmask) ) {
// looks more like 32-bit (like 255.255.255.0) format
if ( true === ($line = $this->_validateNetmask($netmask)) ) {
return $network;
}
return $this->_invalidNetwork($line);
}
return $this->_invalidNetwork(__LINE__);
}
/**
* Validates a 32-bit netmask
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/16 10:34:00 CST
* @author aw
* @desc <p>A netmask is a decimal representation of 32-bit string where the beginning sequence is a complete
* set of 1 (one) followed by a complete set of 0 (zero). If valid the netmask string will be a CIDR numeric
* value and set to the proected property _cidr. If not valid the returned value is the line plus the index if
* the failure is in one of the segments.</p>
* @param string $netmask
* @return true|string
*/
protected function _validateNetmask($netmask) {
$classes = explode('.', $netmask);
if ( 4 !== count($classes) ) {
return __LINE__;
}
$cidr = 0; $end = false;
foreach ( $classes as $index => $segment ) {
if ( !is_numeric($segment) ) {
return __LINE__;
} elseif ( 0 === (int) $segment ) {
$end = true; // all following segment have to be 0 (zero) as well
continue;
}
$matches = array();
// evaluate the binary representation of the segment
$bin = decbin($segment);
if ( 8 !== strlen($bin) || 0 === preg_match('/^([1]{1,8})([0]*)$/', decbin($segment), $matches) ) {
if ( 8 !== strlen($bin) ) {
// this segment is not a complete byte (8 bits) i.e. a value below 128
return __LINE__.':'.++$index; // NOTE: Index begins at 0 (zero)
}
// this segment is a complete byte (8 bits), i.e. a value above 128, but not a valid binary mask (like 11110000)
return __LINE__.':'.++$index; // NOTE: Index begins at 0 (zero)
} elseif ( true === $end ) {
// a mask was found in the previous segment; therefore, this segment should be 0 (zero)
return __LINE__.':'.++$index; // NOTE: Index begins at 0 (zero)
}
$len = strlen($matches[1]);
if ( $len < 8 ) { $end = true; }
$cidr += $len;
}
$this->_cidr = $cidr;
return true;
}
/**
* Validates the network address in a subnet notation
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/16 10:34:00 CST
* @author aw
* @desc <p>The network address in a CIDR or subnet mask notation is the base of the assigned block.
* Because the size of the block is specified by the CIDR or subnet mask the base of a network address
* has to fit and match into the block size. This method evaluates the block size and then validates
* if the base of network address fits into the assigned block. If not valid the line plus the index
* of the failed segment is sent to method _invalidNetwork() triggering or throwing an error.</p>
* @param string $network
* @return true|string
*/
protected function _validateNetwork($network) {
$cidr = $this->getCidr();
$class = $cidr / 8;
// an integer indicates a classful (unicast) network
if ( is_int($class) ) {
$iClass = $class;
$maskBits = 0;
} else {
$iClass = (int) floor($class);
$maskBits = (int) 8 - ($cidr - ($iClass * 8));
$hosts = (int) pow(2, $maskBits); // number of usable hosts in a subnet
}
$segments = explode('.', $network);
// Note: $segments index begins at 0 (zero) and $iClass is the last complete segment in the netmask (8 bits (255))
// It is irrelevant but just to clarify for $iClass: 1 = Class A, 2 = Class B, 3 = Class C
$complete = false;
// check all segments following the last complete class and because we have to check for
// subnetting in the _follow_ class we do NOT add 1 to $iClass as the index in $segments
for ($index = $iClass; $index < 4; $index++) {
$subNetwork = (int) $segments[$index];
if ( 0 === $maskBits ) {
// this class has no subnets (aka classful network)
// all 0 (zero) are expected as (sub)network numbers
if ( 0 !== $subNetwork ) {
return $this->_invalidNetwork(__LINE__.':'.++$index); // NOTE: Index begins at 0 (zero)
}
continue;
} else {
// this class has subnets (aka a classless (subnetted) network)
if ( true === $complete ) {
// for all following networks 0 (zero) is expected as (sub)network number
if ( 0 !== $subNetwork ) {
return $this->_invalidNetwork(__LINE__.':'.++$index); // NOTE: Index begins at 0 (zero)
}
continue;
}
$complete = true;
// the (sub)network must be a fact or hosts(/subnets)
$block = $subNetwork / $hosts;
if ( is_int($block) ) {
// all clear
// NOTE: We do NOT return yet because we may have to verify any following segments
continue;
} else {
return $this->_invalidNetwork(__LINE__.':'.++$index.':'.$hosts); // NOTE: Index begins at 0 (zero)
}
}
}
return true;
}
/**
* Validates a network range with a "from-to" IP address notation
*
* @since Version 0.1.36
* @version 0.1.35 2012/01/16 12:44:00 CST
* @author aw
* @desc <p>A network range can be any difference (or equal) between two valid IP addresses. The method will even switch the
* values if the "to" is lower than the "from" address.</p>
* @param string $range
* @return bool
*/
protected function _validateRange($range) {
list($from,$to) = explode('-', $range); // Note: we do NOT care if more IP ranges have been set, i.e. the range would be invalid
if ( false === ($uInt_from = $this->_makeUnsignedAddress($from)) || false === ($uInt_to = $this->_makeUnsignedAddress($to)) ) {
return $this->_invalidNetwork(__LINE__); // at least one of the addresses is not a valid IP address
}
if ( $uInt_from <= $uInt_to ) {
$this->_rangeFrom = $uInt_from;
$this->_rangeTo = $uInt_to;
} else {
// the range is not in the correct order
$this->_rangeFrom = $uInt_to;
$this->_rangeTo = $uInt_from;
}
return true;
}
/**
* Converts an IP address into an unsigned decimal number (see ATTENTION note for returned value)
*
* @since Version 0.1.36
* @version 0.1.35 2012/01/16 12:31:00 CST
* @author aw
* @desc <p>Uses php function ip2long() to convert the IP into a signed value first and then returns the value with
* sprintf($u). ATTENTION: Function sprintf returns this value as a string and typecasting will not produce the expected
* result for IP addresses above 128.0.0.0. Do not typecast this value to an integer!</p>
* @param string $ip
* @return string
*/
private function _makeUnsignedAddress($ip) {
if ( false === ($ip_addr_long = ip2long($ip)) ) {
// not a valid IP address
return false;
}
// Note ip2long creates signed integers
// a positive number means the address is in the lower half < 128 (0nnn nnnn.)
// a negative number means the address is in the upper half >= 128 (1nnn nnnn.)
// 127.255.255.255 = 2147483647
// 128.0.0.1 = -2147483647
// 128.0.0.0 = -2147483648
// convert to unsigned decimal number
return sprintf('%u',$ip_addr_long);
}
/**
* Triggers an error warning or throws an exception
*
* @since Version 0.1.36
* @version 0.1.36 2012/01/15 11:54:00 CST
* @author aw
* @desc <p>The error message contains the argument which is usually the line where the error occured. The calling method
* may add additional information to the line number.</p>
* @throws E_USER_WARNING If the _throw property is false (default)
* @throws Exception If the _throw property is true
* @param string|int $line
* @return bool (false)
*/
private function _invalidNetwork($line) {
$error_msg = 'The provided network information is not a recognized format [#'.$line.']';
$this->_error(self::INVALID_NETWORK,$error_msg);
$msg = '[SCORES] Application error: '.$error_msg;
if ( false === $this->_throw ) {
trigger_error($msg,E_USER_WARNING);
return false;
} else {
throw new Exception($msg);
}
}
}

View File

@ -0,0 +1,39 @@
This validator class will test an IP against a provide network notation. The
network notation can be a network range, or network address with CIDR or 32-bit
decimal subnet mask notation. Note that the main validation method always uses
the CIDR notation, i.e a bitmask will be converted into a CIDR.
Examples for network notations
------------------------------
Network Range:
**************
128.0.0.12-128.0.0.19
true for all IP addresses inclusively in this range (i.e. from .12 to .19)
CIDR notation:
**************
128.0.0.8/30
block with 4 hosts
true for IP addresses from .8-.11 (i.e. .8, .9, .10, .11)
Subnet mask notation:
*********************
128.0.0.8/255.255.255.252
same as CIDR notation
Special Notes:
--------------
1) The network notation is validated, i.e. you have to pass a valid network and
CIDR or subnet mask combination. For the network range the two values must be
valid IP addresses.
2) A CIDR notation of /32, subnet mask /255.255.255.255 or a range with two
equal addresses will match for one host, i.e. the result is true if the network
address or the range addresses are identical to the IP address
3) The network notation or a range has to be set prior to calling isValid() as
is custom with all Zend validators. The notation can be set when instantiating
the object as an array and 'network' as the index. The setter method is
setNetworkNotation($notation) and expects a string as the argument.

View File

@ -0,0 +1,53 @@
<?php
class Scores_Wkhtml_Pdf
{
protected $wkhtml;
public function __construct()
{
$c = Zend_Registry::get('config');
$this->wkhtml = $c->profil->wkhtmltopdf->path;
}
/**
* Défini les options supplémentaires à l'execution de wkhtmltopdf
* -n, --disable-javascript Do not allow webpages to run javascript.
* --disable-internal-links Do no make local links
* --disable-external-links Do no make links to remote web pages
* --user-style-sheet <url> Specify a user style sheet, to load with every page.
* --print-media-type Use print media-type instead of screen.
* --header-left|right
* @param string $name
* @param string $value
*/
public function setOptions($name, $value = '')
{
$this->options[$name] = $value;
}
/**
* Imprime un fichier HTML en PDF avec l'utilitaire wkhtmltopdf
* @param string $fileIn
* @param string $fileOut
* @return string Nom du fichier
*/
public function exec($fileIn, $fileOut = '')
{
if (empty($fileOut)) {$fileOut = str_replace('.html', '.pdf', $fileIn); }
if(file_exists($fileOut)){ unlink($fileOut); }
$options = '--disable-internal-links';
if ( count($this->options) )
{
foreach ( $this->options as $name => $value )
{
$options.= ' --'.$name;
if ($value!= '') $options.= ' "'.$value.'"';
}
}
$cmd = $this->wkhtml.' '.$options.' "'.$fileIn.'" "'.$fileOut.'"';
exec( $cmd );
return $fileOut;
}
}

View File

@ -0,0 +1,92 @@
<?php
class Scores_Ws_Discover
{
protected $serviceWsdl = null;
protected $serviceOptions = array();
protected $serviceStructure = array();
protected $serviceStructureTypes = array();
protected $serviceTypes;
protected $serviceFunctions;
public function __construct($wsdl, $options = array())
{
$this->serviceWsdl = $wsdl;
$this->serviceOptions = $options;
$this->setStructure();
}
public function getStructure()
{
return $this->serviceStructure;
}
public function getStructureParam()
{
return $this->serviceStructureTypes;
}
protected function setStructure()
{
$client = new Zend_Soap_Client(
$this->serviceWsdl,
$this->serviceOptions
);
$this->serviceFunctions = $client->getFunctions();
$this->serviceTypes = $client->getTypes();
foreach($this->serviceFunctions as $func)
{
$this->setFunction($func);
}
foreach($this->serviceTypes as $type){
$this->setType($type);
}
}
protected function setFunction($func)
{
if (preg_match('/[^\s]+\s([^\s]+)\((.*)\)/', $func, $matches))
{
$funcName = $matches[1];
$funcParams = $matches[2];
$this->serviceStructure[$funcName] = array();
if (preg_match_all('/([^\s]+)\s([^\s]+),?/', $funcParams, $mParams))
{
$nbParams = count($mParams[0]);
for($i=0;$i<$nbParams;$i++)
{
$type = $mParams[1][$i];
$name = $mParams[2][$i];
$this->serviceStructure[$funcName][$i] = array(
'name' => $name,
'type' => $type
);
}
}
}
}
protected function setType($type)
{
$type = str_replace("\n", '', $type);
if (preg_match('/struct\s([^\s]+)\s\{(.*)\}$/m', $type, $matches))
{
$struct = trim($matches[1]);
$params = trim($matches[2]);
preg_match_all('/([^\s]+)\s([^\s]+);/', $params, $paramsMatches);
$nbParams = count($paramsMatches[0]);
$this->serviceStructureTypes[$struct] = array();
for($i=0; $i<$nbParams;$i++)
{
$this->serviceStructureTypes[$struct][$i] = array(
'name' => $paramsMatches[2][$i],
'type' => $paramsMatches[1][$i],
);
}
}
}
}

187
library/Scores/Ws/Doc.php Normal file
View File

@ -0,0 +1,187 @@
<?php
class Scores_Ws_Doc
{
private $serviceClass;
private $classmap = array();
private $serviceMethods = array();
private $serviceTypes = array();
public function __construct($serviceClass = null, $classmap = null, $path)
{
$this->serviceClass = $serviceClass;
$this->classmap = $classmap;
require_once $path . 'Service.php';
$this->parseService();
$this->parseTypes();
}
/**
* Retourne la liste des services et leurs paramètres
* @return array
*/
public function getServiceMethods()
{
return $this->serviceMethods;
}
/**
* Retourne la liste des types de données et leurs paramètres
* @return array
*/
public function getServiceTypes()
{
return $this->serviceTypes;
}
private function parseService()
{
$class = new Zend_Server_Reflection();
$methods = $class->reflectClass($this->serviceClass)
->getMethods();
$methodsElement = array();
foreach ($methods as $method) {
$prototype = null;
$maxNumArgumentsOfPrototype = -1;
foreach ($method->getPrototypes() as $tmpPrototype) {
$numParams = count($tmpPrototype->getParameters());
if ($numParams > $maxNumArgumentsOfPrototype) {
$maxNumArgumentsOfPrototype = $numParams;
$prototype = $tmpPrototype;
}
}
$paramsElement = array();
foreach ($prototype->getParameters() as $param) {
$paramElement = array(
'type' => $param->getType(),
'name' => $param->getName(),
'description' => $param->getDescription(),
);
if ($param->isOptional()){
$paramElement['optional'] = $param->isOptional();
$paramElement['defaultValue'] = $param->getDefaultValue();
}
$paramsElement[] = $paramElement;
}
$methodElement = array(
'name' => $method->getName(),
'desc' => $method->getDescription(),
'params' => $paramsElement,
'return' => $prototype->getReturnType(),
);
$methodsElement[] = $methodElement;
}
$this->serviceMethods = $methodsElement;
}
private function parseTypes()
{
$typesElement = array();
if (count($this->classmap)>0)
{
foreach ($this->classmap as $className)
{
$class = new ReflectionClass($className);
$paramsElement = array();
foreach ($class->getProperties() as $property) {
if ($property->isPublic() && preg_match_all('/@var\s+([^\s]+)/m', $property->getDocComment(), $matches)) {
$name = $property->getName();
$type = $matches[1][0];
/**
* Traitement éléments de documentation à placer dans le WSDL
* Supprime les retours chariots.
* Récupére les éléments de documentation
*/
$comment = '';
$docBlock = preg_replace('/\n/', '', $property->getDocComment() );
if (preg_match('/\/\*\*(.+) \* @var\s+[^\s]+\s+(?:\*|@)/m', $docBlock, $docBlockMatches)) {
$comment.= preg_replace(
array('/\r/', '/\*/' ),
array('' , ''), $docBlockMatches[1]
);
}
/**
* Traitement des @xsd (Provisoire)
* Définition des longueurs dans la documentation
* @xsd minLength=[\d]+ => (Longueur min = [\d]+)
* @xsd maxLength=[\d]+ => (Longueur max = [\d]+)
* @xsd enumeration=element,element
*/
if (preg_match_all('/@xsd\s+(minLength|maxLength)=([\d]+)\s+(?:\*|@)/m', $property->getDocComment(), $resMatches, PREG_SET_ORDER)){
$comment.= '(';
$parcourCpt = 0;
foreach ($resMatches as $res ) {
switch ($res[1]){
case 'minLength':
$comment.= 'Longueur min = '.$res[2];
break;
case 'maxLength':
$comment.= 'Longueur max = '.$res[2];
break;
}
$parcourCpt++;
if ($parcourCpt>0 && $parcourCpt<count($resMatches)) {
$comment.= ', ';
}
}
$comment.= ')';
}
/**
* Traitement des références
* @ref fichier:titre:nom_du_fichier
* => http://vhost/ref/fichier/
* @ref mysql:titre:requete.sql
* => http://vhost/ref/table/
*/
if (preg_match_all('/@ref\s+(fichier|mysql):(.*):(.*)\.(?:csv|sql)\s+(?:\*|@)/m', $property->getDocComment(), $refMatches, PREG_SET_ORDER)){
$view = new Zend_View();
$comment.= ', Référence(s) : ';
foreach ($refMatches as $ref){
switch ($ref[1]){
case 'fichier':
$urlFichier = $view->url(array(
'controller' => 'ref',
'action' => 'fichier',
'q' => $ref[3],
), null, true);
$comment.= '<a href="'.$urlFichier.'">'.$ref[2].'</a>';
break;
case 'mysql':
$urlMysql = $view->url(array(
'controller' => 'ref',
'action' => 'table',
'q' => $ref[3],
), null, true);
$comment.= '<a href="'.$urlMysql.'">'.$ref[2].'</a>';
break;
}
$comment.= ', ';
}
}
$paramElement = array(
'name' => $name,
'type' => $type,
'description' => trim($comment)
);
}
$paramsElement[] = $paramElement;
}
$typesElement[$className] = $paramsElement;
}
$this->serviceTypes = $typesElement;
}
}
}

View File

@ -0,0 +1,2 @@
<?php
class Scores_Ws_Exception extends Zend_Exception {}

View File

@ -0,0 +1,24 @@
<?php
class Scores_Ws_Form_GetIdentite extends Zend_Form
{
public function init()
{
$this->setName('soapform');
$this->setAction('/demo/requete');
$this->setMethod('post');
$this->addElement('text', 'siret', array(
'filters' => array('StringTrim'),
'validators' => array(
array('stringLength',false,array(9,14)),
array('NotEmpty', true),
),
'label' => 'Siret : ',
'required' => 'true',
)
);
$this->addElement('submit', 'submit', array(
'label' => 'Envoyez',
));
}
}

1176
library/Scores/Ws/Server.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,112 @@
<?php
class Scores_Ws_Trigger
{
protected $userInfos;
protected $event;
protected $events = null;
public function __construct($event, $userInfos)
{
$this->event = $event;
$this->userInfos = $userInfos;
}
/**
* Check if we have a trigger to execute
* @return number
*/
protected function hasTrigger()
{
if ( $this->userInfos['Service'] === null ) {
$service = 'default';
}
$model = new Application_Model_Sdv1ClientsServicesTrigger();
$sql = $model->select()
->where('event=?', $this->event)
->where('idClient=?', $this->userInfos['idClient'])
->where('service=?', $service)
->where('login=? OR login=""', $login);
$result = $model->fetchAll($sql);
if ( count($result)>0 ) {
foreach ( $result as $item ) {
$tmp->action = $item->action;
$tmp->params = json_decode($item->actionParams, true);
}
}
return count($result);
}
/**
* Execute all triggers after hasTrigger
* @param array $args
* @return boolean
*/
protected function executeAllTrigger($args)
{
if ( count($this->events)>0 ) {
foreach ( $this->events as $action ) {
$args = array_merge($args, $action->params);
switch ( $action->action ) {
case 'surveillance':
return $this->surveillance($args);
break;
}
}
}
}
/**
* Mise en surveillance automatique
* @param array $args
* source, siren, ...
* @return boolean
*/
protected function surveillance($args)
{
if ( !array_key_exists('source', $args) ) {
return false;
}
if ( !array_key_exists('siren', $args) ) {
return false;
}
if ( !array_key_exists('nic', $args) ) {
return false;
}
if ( empty(trim($this->userInfos['email'])) ) {
return false;
}
if ( array_key_exists('ref', $args)) {
$ref = $args['ref'];
}
try {
$model = new Application_Model_JoSurveillancesSite();
$data = array(
'source' => $args['source'],
'login' => $this->userInfos['login'],
'email' => $this->userInfos['email'],
'siren' => $args['siren'],
'nic' => $args['nic'],
'ref' => $ref,
'encoursClient' => 0,
'rs' => $args['Nom'],
'cp' => $args['CP'],
'ville' => $args['Ville'],
'dateAjout' => date('Y-m-d'),
'dateSuppr' => 0,
);
$model->insert($data);
return true;
} catch (Zend_Db_Exception $e) {
}
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,64 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Acl
*/
require_once 'Zend/Acl.php';
/**
* @see Zend_Acl_Role_Interface
*/
require_once 'Zend/Acl/Role/Interface.php';
/**
* @see Zend_Acl_Resource_Interface
*/
require_once 'Zend/Acl/Resource/Interface.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Acl_Assert_Interface
{
/**
* Returns true if and only if the assertion conditions are met
*
* This method is passed the ACL, Role, Resource, and privilege to which the authorization query applies. If the
* $role, $resource, or $privilege parameters are null, it means that the query applies to all Roles, Resources, or
* privileges, respectively.
*
* @param Zend_Acl $acl
* @param Zend_Acl_Role_Interface $role
* @param Zend_Acl_Resource_Interface $resource
* @param string $privilege
* @return boolean
*/
public function assert(Zend_Acl $acl, Zend_Acl_Role_Interface $role = null, Zend_Acl_Resource_Interface $resource = null,
$privilege = null);
}

View File

@ -1,36 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Acl_Exception extends Zend_Exception
{}

View File

@ -1,75 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Resource.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Acl_Resource_Interface
*/
require_once 'Zend/Acl/Resource/Interface.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Acl_Resource implements Zend_Acl_Resource_Interface
{
/**
* Unique id of Resource
*
* @var string
*/
protected $_resourceId;
/**
* Sets the Resource identifier
*
* @param string $resourceId
* @return void
*/
public function __construct($resourceId)
{
$this->_resourceId = (string) $resourceId;
}
/**
* Defined by Zend_Acl_Resource_Interface; returns the Resource identifier
*
* @return string
*/
public function getResourceId()
{
return $this->_resourceId;
}
/**
* Defined by Zend_Acl_Resource_Interface; returns the Resource identifier
* Proxies to getResourceId()
*
* @return string
*/
public function __toString()
{
return $this->getResourceId();
}
}

View File

@ -1,37 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Acl_Resource_Interface
{
/**
* Returns the string identifier of the Resource
*
* @return string
*/
public function getResourceId();
}

View File

@ -1,75 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Role.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Acl_Role_Interface
*/
require_once 'Zend/Acl/Role/Interface.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Acl_Role implements Zend_Acl_Role_Interface
{
/**
* Unique id of Role
*
* @var string
*/
protected $_roleId;
/**
* Sets the Role identifier
*
* @param string $roleId
* @return void
*/
public function __construct($roleId)
{
$this->_roleId = (string) $roleId;
}
/**
* Defined by Zend_Acl_Role_Interface; returns the Role identifier
*
* @return string
*/
public function getRoleId()
{
return $this->_roleId;
}
/**
* Defined by Zend_Acl_Role_Interface; returns the Role identifier
* Proxies to getRoleId()
*
* @return string
*/
public function __toString()
{
return $this->getRoleId();
}
}

View File

@ -1,37 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Acl_Role_Interface
{
/**
* Returns the string identifier of the Role
*
* @return string
*/
public function getRoleId();
}

View File

@ -1,271 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Registry.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Acl_Role_Interface
*/
require_once 'Zend/Acl/Role/Interface.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Acl_Role_Registry
{
/**
* Internal Role registry data storage
*
* @var array
*/
protected $_roles = array();
/**
* Adds a Role having an identifier unique to the registry
*
* The $parents parameter may be a reference to, or the string identifier for,
* a Role existing in the registry, or $parents may be passed as an array of
* these - mixing string identifiers and objects is ok - to indicate the Roles
* from which the newly added Role will directly inherit.
*
* In order to resolve potential ambiguities with conflicting rules inherited
* from different parents, the most recently added parent takes precedence over
* parents that were previously added. In other words, the first parent added
* will have the least priority, and the last parent added will have the
* highest priority.
*
* @param Zend_Acl_Role_Interface $role
* @param Zend_Acl_Role_Interface|string|array $parents
* @throws Zend_Acl_Role_Registry_Exception
* @return Zend_Acl_Role_Registry Provides a fluent interface
*/
public function add(Zend_Acl_Role_Interface $role, $parents = null)
{
$roleId = $role->getRoleId();
if ($this->has($roleId)) {
/**
* @see Zend_Acl_Role_Registry_Exception
*/
require_once 'Zend/Acl/Role/Registry/Exception.php';
throw new Zend_Acl_Role_Registry_Exception("Role id '$roleId' already exists in the registry");
}
$roleParents = array();
if (null !== $parents) {
if (!is_array($parents)) {
$parents = array($parents);
}
/**
* @see Zend_Acl_Role_Registry_Exception
*/
require_once 'Zend/Acl/Role/Registry/Exception.php';
foreach ($parents as $parent) {
try {
if ($parent instanceof Zend_Acl_Role_Interface) {
$roleParentId = $parent->getRoleId();
} else {
$roleParentId = $parent;
}
$roleParent = $this->get($roleParentId);
} catch (Zend_Acl_Role_Registry_Exception $e) {
throw new Zend_Acl_Role_Registry_Exception("Parent Role id '$roleParentId' does not exist", 0, $e);
}
$roleParents[$roleParentId] = $roleParent;
$this->_roles[$roleParentId]['children'][$roleId] = $role;
}
}
$this->_roles[$roleId] = array(
'instance' => $role,
'parents' => $roleParents,
'children' => array()
);
return $this;
}
/**
* Returns the identified Role
*
* The $role parameter can either be a Role or a Role identifier.
*
* @param Zend_Acl_Role_Interface|string $role
* @throws Zend_Acl_Role_Registry_Exception
* @return Zend_Acl_Role_Interface
*/
public function get($role)
{
if ($role instanceof Zend_Acl_Role_Interface) {
$roleId = $role->getRoleId();
} else {
$roleId = (string) $role;
}
if (!$this->has($role)) {
/**
* @see Zend_Acl_Role_Registry_Exception
*/
require_once 'Zend/Acl/Role/Registry/Exception.php';
throw new Zend_Acl_Role_Registry_Exception("Role '$roleId' not found");
}
return $this->_roles[$roleId]['instance'];
}
/**
* Returns true if and only if the Role exists in the registry
*
* The $role parameter can either be a Role or a Role identifier.
*
* @param Zend_Acl_Role_Interface|string $role
* @return boolean
*/
public function has($role)
{
if ($role instanceof Zend_Acl_Role_Interface) {
$roleId = $role->getRoleId();
} else {
$roleId = (string) $role;
}
return isset($this->_roles[$roleId]);
}
/**
* Returns an array of an existing Role's parents
*
* The array keys are the identifiers of the parent Roles, and the values are
* the parent Role instances. The parent Roles are ordered in this array by
* ascending priority. The highest priority parent Role, last in the array,
* corresponds with the parent Role most recently added.
*
* If the Role does not have any parents, then an empty array is returned.
*
* @param Zend_Acl_Role_Interface|string $role
* @uses Zend_Acl_Role_Registry::get()
* @return array
*/
public function getParents($role)
{
$roleId = $this->get($role)->getRoleId();
return $this->_roles[$roleId]['parents'];
}
/**
* Returns true if and only if $role inherits from $inherit
*
* Both parameters may be either a Role or a Role identifier. If
* $onlyParents is true, then $role must inherit directly from
* $inherit in order to return true. By default, this method looks
* through the entire inheritance DAG to determine whether $role
* inherits from $inherit through its ancestor Roles.
*
* @param Zend_Acl_Role_Interface|string $role
* @param Zend_Acl_Role_Interface|string $inherit
* @param boolean $onlyParents
* @throws Zend_Acl_Role_Registry_Exception
* @return boolean
*/
public function inherits($role, $inherit, $onlyParents = false)
{
/**
* @see Zend_Acl_Role_Registry_Exception
*/
require_once 'Zend/Acl/Role/Registry/Exception.php';
try {
$roleId = $this->get($role)->getRoleId();
$inheritId = $this->get($inherit)->getRoleId();
} catch (Zend_Acl_Role_Registry_Exception $e) {
throw new Zend_Acl_Role_Registry_Exception($e->getMessage(), $e->getCode(), $e);
}
$inherits = isset($this->_roles[$roleId]['parents'][$inheritId]);
if ($inherits || $onlyParents) {
return $inherits;
}
foreach ($this->_roles[$roleId]['parents'] as $parentId => $parent) {
if ($this->inherits($parentId, $inheritId)) {
return true;
}
}
return false;
}
/**
* Removes the Role from the registry
*
* The $role parameter can either be a Role or a Role identifier.
*
* @param Zend_Acl_Role_Interface|string $role
* @throws Zend_Acl_Role_Registry_Exception
* @return Zend_Acl_Role_Registry Provides a fluent interface
*/
public function remove($role)
{
/**
* @see Zend_Acl_Role_Registry_Exception
*/
require_once 'Zend/Acl/Role/Registry/Exception.php';
try {
$roleId = $this->get($role)->getRoleId();
} catch (Zend_Acl_Role_Registry_Exception $e) {
throw new Zend_Acl_Role_Registry_Exception($e->getMessage(), $e->getCode(), $e);
}
foreach ($this->_roles[$roleId]['children'] as $childId => $child) {
unset($this->_roles[$childId]['parents'][$roleId]);
}
foreach ($this->_roles[$roleId]['parents'] as $parentId => $parent) {
unset($this->_roles[$parentId]['children'][$roleId]);
}
unset($this->_roles[$roleId]);
return $this;
}
/**
* Removes all Roles from the registry
*
* @return Zend_Acl_Role_Registry Provides a fluent interface
*/
public function removeAll()
{
$this->_roles = array();
return $this;
}
public function getRoles()
{
return $this->_roles;
}
}

View File

@ -1,36 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Acl_Exception
*/
require_once 'Zend/Acl/Exception.php';
/**
* @category Zend
* @package Zend_Acl
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Acl_Role_Registry_Exception extends Zend_Acl_Exception
{}

View File

@ -1,133 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Auth.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Amf_Auth_Abstract */
require_once 'Zend/Amf/Auth/Abstract.php';
/** @see Zend_Acl */
require_once 'Zend/Acl.php';
/** @see Zend_Auth_Result */
require_once 'Zend/Auth/Result.php';
/**
* This class implements authentication against XML file with roles for Flex Builder.
*
* @package Zend_Amf
* @subpackage Adobe
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Adobe_Auth extends Zend_Amf_Auth_Abstract
{
/**
* ACL for authorization
*
* @var Zend_Acl
*/
protected $_acl;
/**
* Username/password array
*
* @var array
*/
protected $_users = array();
/**
* Create auth adapter
*
* @param string $rolefile File containing XML with users and roles
*/
public function __construct($rolefile)
{
$this->_acl = new Zend_Acl();
$xml = simplexml_load_file($rolefile);
/*
Roles file format:
<roles>
<role id=”admin”>
<user name=”user1” password=”pwd”/>
</role>
<role id=”hr”>
<user name=”user2” password=”pwd2”/>
</role>
</roles>
*/
foreach($xml->role as $role) {
$this->_acl->addRole(new Zend_Acl_Role((string)$role["id"]));
foreach($role->user as $user) {
$this->_users[(string)$user["name"]] = array("password" => (string)$user["password"],
"role" => (string)$role["id"]);
}
}
}
/**
* Get ACL with roles from XML file
*
* @return Zend_Acl
*/
public function getAcl()
{
return $this->_acl;
}
/**
* Perform authentication
*
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
* @see Zend_Auth_Adapter_Interface#authenticate()
*/
public function authenticate()
{
if (empty($this->_username) ||
empty($this->_password)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Username/password should be set');
}
if(!isset($this->_users[$this->_username])) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
null,
array('Username not found')
);
}
$user = $this->_users[$this->_username];
if($user["password"] != $this->_password) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
null,
array('Authentication failed')
);
}
$id = new stdClass();
$id->role = $user["role"];
$id->name = $this->_username;
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $id);
}
}

View File

@ -1,103 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: DbInspector.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This class implements authentication against XML file with roles for Flex Builder.
*
* @package Zend_Amf
* @subpackage Adobe
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Adobe_DbInspector
{
/**
* Connect to the database
*
* @param string $dbType Database adapter type for Zend_Db
* @param array|object $dbDescription Adapter-specific connection settings
* @return Zend_Db_Adapter_Abstract
* @see Zend_Db::factory()
*/
protected function _connect($dbType, $dbDescription)
{
if(is_object($dbDescription)) {
$dbDescription = get_object_vars($dbDescription);
}
return Zend_Db::factory($dbType, $dbDescription);
}
/**
* Describe database object.
*
* Usage example:
* $inspector->describeTable('Pdo_Mysql',
* array(
* 'host' => '127.0.0.1',
* 'username' => 'webuser',
* 'password' => 'xxxxxxxx',
* 'dbname' => 'test'
* ),
* 'mytable'
* );
*
* @param string $dbType Database adapter type for Zend_Db
* @param array|object $dbDescription Adapter-specific connection settings
* @param string $tableName Table name
* @return array Table description
* @see Zend_Db::describeTable()
* @see Zend_Db::factory()
*/
public function describeTable($dbType, $dbDescription, $tableName)
{
$db = $this->_connect($dbType, $dbDescription);
return $db->describeTable($tableName);
}
/**
* Test database connection
*
* @param string $dbType Database adapter type for Zend_Db
* @param array|object $dbDescription Adapter-specific connection settings
* @return bool
* @see Zend_Db::factory()
*/
public function connect($dbType, $dbDescription)
{
$db = $this->_connect($dbType, $dbDescription);
$db->listTables();
return true;
}
/**
* Get the list of database tables
*
* @param string $dbType Database adapter type for Zend_Db
* @param array|object $dbDescription Adapter-specific connection settings
* @return array List of the tables
*/
public function getTables($dbType, $dbDescription)
{
$db = $this->_connect($dbType, $dbDescription);
return $db->listTables();
}
}

View File

@ -1,318 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Introspector.php 23953 2011-05-03 05:47:39Z ralph $
*/
/** @see Zend_Amf_Parse_TypeLoader */
require_once 'Zend/Amf/Parse/TypeLoader.php';
/** @see Zend_Reflection_Class */
require_once 'Zend/Reflection/Class.php';
/** @see Zend_Server_Reflection */
require_once 'Zend/Server/Reflection.php';
/**
* This class implements a service for generating AMF service descriptions as XML.
*
* @package Zend_Amf
* @subpackage Adobe
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Adobe_Introspector
{
/**
* Options used:
* - server: instance of Zend_Amf_Server to use
* - directories: directories where class files may be looked up
*
* @var array Introspector options
*/
protected $_options;
/**
* @var DOMElement DOM element to store types
*/
protected $_types;
/**
* @var array Map of the known types
*/
protected $_typesMap = array();
/**
* @var DOMDocument XML document to store data
*/
protected $_xml;
/**
* Constructor
*
* @return void
*/
public function __construct()
{
$this->_xml = new DOMDocument('1.0', 'utf-8');
}
/**
* Create XML definition on an AMF service class
*
* @param string $serviceClass Service class name
* @param array $options invocation options
* @return string XML with service class introspection
*/
public function introspect($serviceClass, $options = array())
{
$this->_options = $options;
if (strpbrk($serviceClass, '\\/<>')) {
return $this->_returnError('Invalid service name');
}
// Transform com.foo.Bar into com_foo_Bar
$serviceClass = str_replace('.' , '_', $serviceClass);
// Introspect!
if (!class_exists($serviceClass)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($serviceClass, $this->_getServicePath());
}
$serv = $this->_xml->createElement('service-description');
$serv->setAttribute('xmlns', 'http://ns.adobe.com/flex/service-description/2008');
$this->_types = $this->_xml->createElement('types');
$this->_ops = $this->_xml->createElement('operations');
$r = Zend_Server_Reflection::reflectClass($serviceClass);
$this->_addService($r, $this->_ops);
$serv->appendChild($this->_types);
$serv->appendChild($this->_ops);
$this->_xml->appendChild($serv);
return $this->_xml->saveXML();
}
/**
* Authentication handler
*
* @param Zend_Acl $acl
* @return unknown_type
*/
public function initAcl(Zend_Acl $acl)
{
return false; // we do not need auth for this class
}
/**
* Generate map of public class attributes
*
* @param string $typename type name
* @param DOMElement $typexml target XML element
* @return void
*/
protected function _addClassAttributes($typename, DOMElement $typexml)
{
// Do not try to autoload here because _phpTypeToAS should
// have already attempted to load this class
if (!class_exists($typename, false)) {
return;
}
$rc = new Zend_Reflection_Class($typename);
foreach ($rc->getProperties() as $prop) {
if (!$prop->isPublic()) {
continue;
}
$propxml = $this->_xml->createElement('property');
$propxml->setAttribute('name', $prop->getName());
$type = $this->_registerType($this->_getPropertyType($prop));
$propxml->setAttribute('type', $type);
$typexml->appendChild($propxml);
}
}
/**
* Build XML service description from reflection class
*
* @param Zend_Server_Reflection_Class $refclass
* @param DOMElement $target target XML element
* @return void
*/
protected function _addService(Zend_Server_Reflection_Class $refclass, DOMElement $target)
{
foreach ($refclass->getMethods() as $method) {
if (!$method->isPublic()
|| $method->isConstructor()
|| ('__' == substr($method->name, 0, 2))
) {
continue;
}
foreach ($method->getPrototypes() as $proto) {
$op = $this->_xml->createElement('operation');
$op->setAttribute('name', $method->getName());
$rettype = $this->_registerType($proto->getReturnType());
$op->setAttribute('returnType', $rettype);
foreach ($proto->getParameters() as $param) {
$arg = $this->_xml->createElement('argument');
$arg->setAttribute('name', $param->getName());
$type = $param->getType();
if ($type == 'mixed' && ($pclass = $param->getClass())) {
$type = $pclass->getName();
}
$ptype = $this->_registerType($type);
$arg->setAttribute('type', $ptype);
if($param->isDefaultValueAvailable()) {
$arg->setAttribute('defaultvalue', $param->getDefaultValue());
}
$op->appendChild($arg);
}
$target->appendChild($op);
}
}
}
/**
* Extract type of the property from DocBlock
*
* @param Zend_Reflection_Property $prop reflection property object
* @return string Property type
*/
protected function _getPropertyType(Zend_Reflection_Property $prop)
{
$docBlock = $prop->getDocComment();
if (!$docBlock) {
return 'Unknown';
}
if (!$docBlock->hasTag('var')) {
return 'Unknown';
}
$tag = $docBlock->getTag('var');
return trim($tag->getDescription());
}
/**
* Get the array of service directories
*
* @return array Service class directories
*/
protected function _getServicePath()
{
if (isset($this->_options['server'])) {
return $this->_options['server']->getDirectory();
}
if (isset($this->_options['directories'])) {
return $this->_options['directories'];
}
return array();
}
/**
* Map from PHP type name to AS type name
*
* @param string $typename PHP type name
* @return string AS type name
*/
protected function _phpTypeToAS($typename)
{
if (class_exists($typename)) {
$vars = get_class_vars($typename);
if (isset($vars['_explicitType'])) {
return $vars['_explicitType'];
}
}
if (false !== ($asname = Zend_Amf_Parse_TypeLoader::getMappedClassName($typename))) {
return $asname;
}
return $typename;
}
/**
* Register new type on the system
*
* @param string $typename type name
* @return string New type name
*/
protected function _registerType($typename)
{
// Known type - return its AS name
if (isset($this->_typesMap[$typename])) {
return $this->_typesMap[$typename];
}
// Standard types
if (in_array($typename, array('void', 'null', 'mixed', 'unknown_type'))) {
return 'Unknown';
}
// Arrays
if ('array' == $typename) {
return 'Unknown[]';
}
if (in_array($typename, array('int', 'integer', 'bool', 'boolean', 'float', 'string', 'object', 'Unknown', 'stdClass'))) {
return $typename;
}
// Resolve and store AS name
$asTypeName = $this->_phpTypeToAS($typename);
$this->_typesMap[$typename] = $asTypeName;
// Create element for the name
$typeEl = $this->_xml->createElement('type');
$typeEl->setAttribute('name', $asTypeName);
$this->_addClassAttributes($typename, $typeEl);
$this->_types->appendChild($typeEl);
return $asTypeName;
}
/**
* Return error with error message
*
* @param string $msg Error message
* @return string
*/
protected function _returnError($msg)
{
return 'ERROR: $msg';
}
}

View File

@ -1,42 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Auth_Adapter_Interface */
require_once 'Zend/Auth/Adapter/Interface.php';
/**
* Base abstract class for AMF authentication implementation
*
* @package Zend_Amf
* @subpackage Auth
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Amf_Auth_Abstract implements Zend_Auth_Adapter_Interface
{
protected $_username;
protected $_password;
public function setCredentials($username, $password) {
$this->_username = $username;
$this->_password = $password;
}
}

View File

@ -1,87 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Constants.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* The following constants are used throughout serialization and
* deserialization to detect the AMF marker and encoding types.
*
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
final class Zend_Amf_Constants
{
const AMF0_NUMBER = 0x00;
const AMF0_BOOLEAN = 0x01;
const AMF0_STRING = 0x02;
const AMF0_OBJECT = 0x03;
const AMF0_MOVIECLIP = 0x04;
const AMF0_NULL = 0x05;
const AMF0_UNDEFINED = 0x06;
const AMF0_REFERENCE = 0x07;
const AMF0_MIXEDARRAY = 0x08;
const AMF0_OBJECTTERM = 0x09;
const AMF0_ARRAY = 0x0a;
const AMF0_DATE = 0x0b;
const AMF0_LONGSTRING = 0x0c;
const AMF0_UNSUPPORTED = 0x0e;
const AMF0_XML = 0x0f;
const AMF0_TYPEDOBJECT = 0x10;
const AMF0_AMF3 = 0x11;
const AMF0_OBJECT_ENCODING = 0x00;
const AMF3_UNDEFINED = 0x00;
const AMF3_NULL = 0x01;
const AMF3_BOOLEAN_FALSE = 0x02;
const AMF3_BOOLEAN_TRUE = 0x03;
const AMF3_INTEGER = 0x04;
const AMF3_NUMBER = 0x05;
const AMF3_STRING = 0x06;
const AMF3_XML = 0x07;
const AMF3_DATE = 0x08;
const AMF3_ARRAY = 0x09;
const AMF3_OBJECT = 0x0A;
const AMF3_XMLSTRING = 0x0B;
const AMF3_BYTEARRAY = 0x0C;
const AMF3_OBJECT_ENCODING = 0x03;
// Object encodings for AMF3 object types
const ET_PROPLIST = 0x00;
const ET_EXTERNAL = 0x01;
const ET_DYNAMIC = 0x02;
const ET_PROXY = 0x03;
const FMS_OBJECT_ENCODING = 0x01;
/**
* Special content length value that indicates "unknown" content length
* per AMF Specification
*/
const UNKNOWN_CONTENT_LENGTH = -1;
const URL_APPEND_HEADER = 'AppendToGatewayUrl';
const RESULT_METHOD = '/onResult';
const STATUS_METHOD = '/onStatus';
const CREDENTIALS_HEADER = 'Credentials';
const PERSISTENT_HEADER = 'RequestPersistentHeader';
const DESCRIBE_HEADER = 'DescribeService';
const GUEST_ROLE = 'anonymous';
}

View File

@ -1,34 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Exception
*/
require_once 'Zend/Exception.php';
/**
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Exception extends Zend_Exception
{
}

View File

@ -1,306 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse_Amf0
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Deserializer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** @see Zend_Amf_Parse_Deserializer */
require_once 'Zend/Amf/Parse/Deserializer.php';
/**
* Read an AMF0 input stream and convert it into PHP data types
*
* @todo Implement Typed Object Class Mapping
* @todo Class could be implemented as Factory Class with each data type it's own class
* @package Zend_Amf
* @subpackage Parse_Amf0
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Amf0_Deserializer extends Zend_Amf_Parse_Deserializer
{
/**
* An array of objects used for recursively deserializing an object.
* @var array
*/
protected $_reference = array();
/**
* If AMF3 serialization occurs, update to AMF0 0x03
*
* @var int
*/
protected $_objectEncoding = Zend_Amf_Constants::AMF0_OBJECT_ENCODING;
/**
* Read AMF markers and dispatch for deserialization
*
* Checks for AMF marker types and calls the appropriate methods
* for deserializing those marker types. Markers are the data type of
* the following value.
*
* @param integer $typeMarker
* @return mixed whatever the data type is of the marker in php
* @throws Zend_Amf_Exception for invalid type
*/
public function readTypeMarker($typeMarker = null)
{
if ($typeMarker === null) {
$typeMarker = $this->_stream->readByte();
}
switch($typeMarker) {
// number
case Zend_Amf_Constants::AMF0_NUMBER:
return $this->_stream->readDouble();
// boolean
case Zend_Amf_Constants::AMF0_BOOLEAN:
return (boolean) $this->_stream->readByte();
// string
case Zend_Amf_Constants::AMF0_STRING:
return $this->_stream->readUTF();
// object
case Zend_Amf_Constants::AMF0_OBJECT:
return $this->readObject();
// null
case Zend_Amf_Constants::AMF0_NULL:
return null;
// undefined
case Zend_Amf_Constants::AMF0_UNDEFINED:
return null;
// Circular references are returned here
case Zend_Amf_Constants::AMF0_REFERENCE:
return $this->readReference();
// mixed array with numeric and string keys
case Zend_Amf_Constants::AMF0_MIXEDARRAY:
return $this->readMixedArray();
// array
case Zend_Amf_Constants::AMF0_ARRAY:
return $this->readArray();
// date
case Zend_Amf_Constants::AMF0_DATE:
return $this->readDate();
// longString strlen(string) > 2^16
case Zend_Amf_Constants::AMF0_LONGSTRING:
return $this->_stream->readLongUTF();
//internal AS object, not supported
case Zend_Amf_Constants::AMF0_UNSUPPORTED:
return null;
// XML
case Zend_Amf_Constants::AMF0_XML:
return $this->readXmlString();
// typed object ie Custom Class
case Zend_Amf_Constants::AMF0_TYPEDOBJECT:
return $this->readTypedObject();
//AMF3-specific
case Zend_Amf_Constants::AMF0_AMF3:
return $this->readAmf3TypeMarker();
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported marker type: ' . $typeMarker);
}
}
/**
* Read AMF objects and convert to PHP objects
*
* Read the name value pair objects form the php message and convert them to
* a php object class.
*
* Called when the marker type is 3.
*
* @param array|null $object
* @return object
*/
public function readObject($object = null)
{
if ($object === null) {
$object = array();
}
while (true) {
$key = $this->_stream->readUTF();
$typeMarker = $this->_stream->readByte();
if ($typeMarker != Zend_Amf_Constants::AMF0_OBJECTTERM ){
//Recursivly call readTypeMarker to get the types of properties in the object
$object[$key] = $this->readTypeMarker($typeMarker);
} else {
//encountered AMF object terminator
break;
}
}
$this->_reference[] = $object;
return (object) $object;
}
/**
* Read reference objects
*
* Used to gain access to the private array of reference objects.
* Called when marker type is 7.
*
* @return object
* @throws Zend_Amf_Exception for invalid reference keys
*/
public function readReference()
{
$key = $this->_stream->readInt();
if (!array_key_exists($key, $this->_reference)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid reference key: '. $key);
}
return $this->_reference[$key];
}
/**
* Reads an array with numeric and string indexes.
*
* Called when marker type is 8
*
* @todo As of Flash Player 9 there is not support for mixed typed arrays
* so we handle this as an object. With the introduction of vectors
* in Flash Player 10 this may need to be reconsidered.
* @return array
*/
public function readMixedArray()
{
$length = $this->_stream->readLong();
return $this->readObject();
}
/**
* Converts numerically indexed actiosncript arrays into php arrays.
*
* Called when marker type is 10
*
* @return array
*/
public function readArray()
{
$length = $this->_stream->readLong();
$array = array();
while ($length--) {
$array[] = $this->readTypeMarker();
}
return $array;
}
/**
* Convert AS Date to Zend_Date
*
* @return Zend_Date
*/
public function readDate()
{
// get the unix time stamp. Not sure why ActionScript does not use
// milliseconds
$timestamp = floor($this->_stream->readDouble() / 1000);
// The timezone offset is never returned to the server; it is always 0,
// so read and ignore.
$offset = $this->_stream->readInt();
require_once 'Zend/Date.php';
$date = new Zend_Date($timestamp);
return $date;
}
/**
* Convert XML to SimpleXml
* If user wants DomDocument they can use dom_import_simplexml
*
* @return SimpleXml Object
*/
public function readXmlString()
{
$string = $this->_stream->readLongUTF();
return simplexml_load_string($string);
}
/**
* Read Class that is to be mapped to a server class.
*
* Commonly used for Value Objects on the server
*
* @todo implement Typed Class mapping
* @return object|array
* @throws Zend_Amf_Exception if unable to load type
*/
public function readTypedObject()
{
require_once 'Zend/Amf/Parse/TypeLoader.php';
// get the remote class name
$className = $this->_stream->readUTF();
$loader = Zend_Amf_Parse_TypeLoader::loadType($className);
$returnObject = new $loader();
$properties = get_object_vars($this->readObject());
foreach($properties as $key=>$value) {
if($key) {
$returnObject->$key = $value;
}
}
if($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) {
$returnObject = get_object_vars($returnObject);
}
return $returnObject;
}
/**
* AMF3 data type encountered load AMF3 Deserializer to handle
* type markers.
*
* @return string
*/
public function readAmf3TypeMarker()
{
require_once 'Zend/Amf/Parse/Amf3/Deserializer.php';
$deserializer = new Zend_Amf_Parse_Amf3_Deserializer($this->_stream);
$this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING;
return $deserializer->readTypeMarker();
}
/**
* Return the object encoding to check if an AMF3 object
* is going to be return.
*
* @return int
*/
public function getObjectEncoding()
{
return $this->_objectEncoding;
}
}

View File

@ -1,362 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse_Amf0
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Serializer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** @see Zend_Amf_Parse_Serializer */
require_once 'Zend/Amf/Parse/Serializer.php';
/**
* Serializer PHP misc types back to there corresponding AMF0 Type Marker.
*
* @uses Zend_Amf_Parse_Serializer
* @package Zend_Amf
* @subpackage Parse_Amf0
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Amf0_Serializer extends Zend_Amf_Parse_Serializer
{
/**
* @var string Name of the class to be returned
*/
protected $_className = '';
/**
* An array of reference objects
* @var array
*/
protected $_referenceObjects = array();
/**
* Determine type and serialize accordingly
*
* Checks to see if the type was declared and then either
* auto negotiates the type or relies on the user defined markerType to
* serialize the data into amf
*
* @param mixed $data
* @param mixed $markerType
* @param mixed $dataByVal
* @return Zend_Amf_Parse_Amf0_Serializer
* @throws Zend_Amf_Exception for unrecognized types or data
*/
public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $data) && ($dataByVal !== false)) {
$data = &$dataByVal;
}
if (null !== $markerType) {
//try to reference the given object
if (!$this->writeObjectReference($data, $markerType)) {
// Write the Type Marker to denote the following action script data type
$this->_stream->writeByte($markerType);
switch($markerType) {
case Zend_Amf_Constants::AMF0_NUMBER:
$this->_stream->writeDouble($data);
break;
case Zend_Amf_Constants::AMF0_BOOLEAN:
$this->_stream->writeByte($data);
break;
case Zend_Amf_Constants::AMF0_STRING:
$this->_stream->writeUTF($data);
break;
case Zend_Amf_Constants::AMF0_OBJECT:
$this->writeObject($data);
break;
case Zend_Amf_Constants::AMF0_NULL:
break;
case Zend_Amf_Constants::AMF0_REFERENCE:
$this->_stream->writeInt($data);
break;
case Zend_Amf_Constants::AMF0_MIXEDARRAY:
// Write length of numeric keys as zero.
$this->_stream->writeLong(0);
$this->writeObject($data);
break;
case Zend_Amf_Constants::AMF0_ARRAY:
$this->writeArray($data);
break;
case Zend_Amf_Constants::AMF0_DATE:
$this->writeDate($data);
break;
case Zend_Amf_Constants::AMF0_LONGSTRING:
$this->_stream->writeLongUTF($data);
break;
case Zend_Amf_Constants::AMF0_TYPEDOBJECT:
$this->writeTypedObject($data);
break;
case Zend_Amf_Constants::AMF0_AMF3:
$this->writeAmf3TypeMarker($data);
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception("Unknown Type Marker: " . $markerType);
}
}
} else {
if (is_resource($data)) {
$data = Zend_Amf_Parse_TypeLoader::handleResource($data);
}
switch (true) {
case (is_int($data) || is_float($data)):
$markerType = Zend_Amf_Constants::AMF0_NUMBER;
break;
case (is_bool($data)):
$markerType = Zend_Amf_Constants::AMF0_BOOLEAN;
break;
case (is_string($data) && (strlen($data) > 65536)):
$markerType = Zend_Amf_Constants::AMF0_LONGSTRING;
break;
case (is_string($data)):
$markerType = Zend_Amf_Constants::AMF0_STRING;
break;
case (is_object($data)):
if (($data instanceof DateTime) || ($data instanceof Zend_Date)) {
$markerType = Zend_Amf_Constants::AMF0_DATE;
} else {
if($className = $this->getClassName($data)){
//Object is a Typed object set classname
$markerType = Zend_Amf_Constants::AMF0_TYPEDOBJECT;
$this->_className = $className;
} else {
// Object is a generic classname
$markerType = Zend_Amf_Constants::AMF0_OBJECT;
}
break;
}
break;
case (null === $data):
$markerType = Zend_Amf_Constants::AMF0_NULL;
break;
case (is_array($data)):
// check if it is an associative array
$i = 0;
foreach (array_keys($data) as $key) {
// check if it contains non-integer keys
if (!is_numeric($key) || intval($key) != $key) {
$markerType = Zend_Amf_Constants::AMF0_OBJECT;
break;
// check if it is a sparse indexed array
} else if ($key != $i) {
$markerType = Zend_Amf_Constants::AMF0_MIXEDARRAY;
break;
}
$i++;
}
// Dealing with a standard numeric array
if(!$markerType){
$markerType = Zend_Amf_Constants::AMF0_ARRAY;
break;
}
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data));
}
$this->writeTypeMarker($data, $markerType);
}
return $this;
}
/**
* Check if the given object is in the reference table, write the reference if it exists,
* otherwise add the object to the reference table
*
* @param mixed $object object reference to check for reference
* @param string $markerType AMF type of the object to write
* @param mixed $objectByVal object to check for reference
* @return Boolean true, if the reference was written, false otherwise
*/
protected function writeObjectReference(&$object, $markerType, $objectByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $object) && ($objectByVal !== false)) {
$object = &$objectByVal;
}
if ($markerType == Zend_Amf_Constants::AMF0_OBJECT
|| $markerType == Zend_Amf_Constants::AMF0_MIXEDARRAY
|| $markerType == Zend_Amf_Constants::AMF0_ARRAY
|| $markerType == Zend_Amf_Constants::AMF0_TYPEDOBJECT
) {
$ref = array_search($object, $this->_referenceObjects, true);
//handle object reference
if($ref !== false){
$this->writeTypeMarker($ref,Zend_Amf_Constants::AMF0_REFERENCE);
return true;
}
$this->_referenceObjects[] = $object;
}
return false;
}
/**
* Write a PHP array with string or mixed keys.
*
* @param object $data
* @return Zend_Amf_Parse_Amf0_Serializer
*/
public function writeObject($object)
{
// Loop each element and write the name of the property.
foreach ($object as $key => &$value) {
// skip variables starting with an _ private transient
if( $key[0] == "_") continue;
$this->_stream->writeUTF($key);
$this->writeTypeMarker($value);
}
// Write the end object flag
$this->_stream->writeInt(0);
$this->_stream->writeByte(Zend_Amf_Constants::AMF0_OBJECTTERM);
return $this;
}
/**
* Write a standard numeric array to the output stream. If a mixed array
* is encountered call writeTypeMarker with mixed array.
*
* @param array $array
* @return Zend_Amf_Parse_Amf0_Serializer
*/
public function writeArray(&$array)
{
$length = count($array);
if (!$length < 0) {
// write the length of the array
$this->_stream->writeLong(0);
} else {
// Write the length of the numeric array
$this->_stream->writeLong($length);
for ($i=0; $i<$length; $i++) {
$value = isset($array[$i]) ? $array[$i] : null;
$this->writeTypeMarker($value);
}
}
return $this;
}
/**
* Convert the DateTime into an AMF Date
*
* @param DateTime|Zend_Date $data
* @return Zend_Amf_Parse_Amf0_Serializer
*/
public function writeDate($data)
{
if ($data instanceof DateTime) {
$dateString = $data->format('U');
} elseif ($data instanceof Zend_Date) {
$dateString = $data->toString('U');
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid date specified; must be a DateTime or Zend_Date object');
}
$dateString *= 1000;
// Make the conversion and remove milliseconds.
$this->_stream->writeDouble($dateString);
// Flash does not respect timezone but requires it.
$this->_stream->writeInt(0);
return $this;
}
/**
* Write a class mapped object to the output stream.
*
* @param object $data
* @return Zend_Amf_Parse_Amf0_Serializer
*/
public function writeTypedObject($data)
{
$this->_stream->writeUTF($this->_className);
$this->writeObject($data);
return $this;
}
/**
* Encountered and AMF3 Type Marker use AMF3 serializer. Once AMF3 is
* encountered it will not return to AMf0.
*
* @param string $data
* @return Zend_Amf_Parse_Amf0_Serializer
*/
public function writeAmf3TypeMarker(&$data)
{
require_once 'Zend/Amf/Parse/Amf3/Serializer.php';
$serializer = new Zend_Amf_Parse_Amf3_Serializer($this->_stream);
$serializer->writeTypeMarker($data);
return $this;
}
/**
* Find if the class name is a class mapped name and return the
* respective classname if it is.
*
* @param object $object
* @return false|string $className
*/
protected function getClassName($object)
{
require_once 'Zend/Amf/Parse/TypeLoader.php';
//Check to see if the object is a typed object and we need to change
$className = '';
switch (true) {
// the return class mapped name back to actionscript class name.
case Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object)):
$className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object));
break;
// Check to see if the user has defined an explicit Action Script type.
case isset($object->_explicitType):
$className = $object->_explicitType;
break;
// Check if user has defined a method for accessing the Action Script type
case method_exists($object, 'getASClassName'):
$className = $object->getASClassName();
break;
// No return class name is set make it a generic object
case ($object instanceof stdClass):
$className = '';
break;
// By default, use object's class name
default:
$className = get_class($object);
break;
}
if(!$className == '') {
return $className;
} else {
return false;
}
}
}

View File

@ -1,421 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse_Amf3
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Deserializer.php 24138 2011-06-14 01:38:34Z adamlundrigan $
*/
/** Zend_Amf_Parse_Deserializer */
require_once 'Zend/Amf/Parse/Deserializer.php';
/** Zend_Amf_Parse_TypeLoader */
require_once 'Zend/Amf/Parse/TypeLoader.php';
/**
* Read an AMF3 input stream and convert it into PHP data types.
*
* @todo readObject to handle Typed Objects
* @todo readXMLStrimg to be implemented.
* @todo Class could be implemented as Factory Class with each data type it's own class.
* @package Zend_Amf
* @subpackage Parse_Amf3
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Amf3_Deserializer extends Zend_Amf_Parse_Deserializer
{
/**
* Total number of objects in the referenceObject array
* @var int
*/
protected $_objectCount;
/**
* An array of reference objects per amf body
* @var array
*/
protected $_referenceObjects = array();
/**
* An array of reference strings per amf body
* @var array
*/
protected $_referenceStrings = array();
/**
* An array of reference class definitions per body
* @var array
*/
protected $_referenceDefinitions = array();
/**
* Read AMF markers and dispatch for deserialization
*
* Checks for AMF marker types and calls the appropriate methods
* for deserializing those marker types. markers are the data type of
* the following value.
*
* @param integer $typeMarker
* @return mixed Whatever the corresponding PHP data type is
* @throws Zend_Amf_Exception for unidentified marker type
*/
public function readTypeMarker($typeMarker = null)
{
if(null === $typeMarker) {
$typeMarker = $this->_stream->readByte();
}
switch($typeMarker) {
case Zend_Amf_Constants::AMF3_UNDEFINED:
return null;
case Zend_Amf_Constants::AMF3_NULL:
return null;
case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE:
return false;
case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE:
return true;
case Zend_Amf_Constants::AMF3_INTEGER:
return $this->readInteger();
case Zend_Amf_Constants::AMF3_NUMBER:
return $this->_stream->readDouble();
case Zend_Amf_Constants::AMF3_STRING:
return $this->readString();
case Zend_Amf_Constants::AMF3_DATE:
return $this->readDate();
case Zend_Amf_Constants::AMF3_ARRAY:
return $this->readArray();
case Zend_Amf_Constants::AMF3_OBJECT:
return $this->readObject();
case Zend_Amf_Constants::AMF3_XML:
case Zend_Amf_Constants::AMF3_XMLSTRING:
return $this->readXmlString();
case Zend_Amf_Constants::AMF3_BYTEARRAY:
return $this->readString();
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported type marker: ' . $typeMarker);
}
}
/**
* Read and deserialize an integer
*
* AMF 3 represents smaller integers with fewer bytes using the most
* significant bit of each byte. The worst case uses 32-bits
* to represent a 29-bit number, which is what we would have
* done with no compression.
* - 0x00000000 - 0x0000007F : 0xxxxxxx
* - 0x00000080 - 0x00003FFF : 1xxxxxxx 0xxxxxxx
* - 0x00004000 - 0x001FFFFF : 1xxxxxxx 1xxxxxxx 0xxxxxxx
* - 0x00200000 - 0x3FFFFFFF : 1xxxxxxx 1xxxxxxx 1xxxxxxx xxxxxxxx
* - 0x40000000 - 0xFFFFFFFF : throw range exception
*
* 0x04 -> integer type code, followed by up to 4 bytes of data.
*
* Parsing integers on OSFlash for the AMF3 integer data format:
* @link http://osflash.org/amf3/parsing_integers
* @return int|float
*/
public function readInteger()
{
$count = 1;
$intReference = $this->_stream->readByte();
$result = 0;
while ((($intReference & 0x80) != 0) && $count < 4) {
$result <<= 7;
$result |= ($intReference & 0x7f);
$intReference = $this->_stream->readByte();
$count++;
}
if ($count < 4) {
$result <<= 7;
$result |= $intReference;
} else {
// Use all 8 bits from the 4th byte
$result <<= 8;
$result |= $intReference;
// Check if the integer should be negative
if (($result & 0x10000000) != 0) {
//and extend the sign bit
$result |= ~0xFFFFFFF;
}
}
return $result;
}
/**
* Read and deserialize a string
*
* Strings can be sent as a reference to a previously
* occurring String by using an index to the implicit string reference table.
* Strings are encoding using UTF-8 - however the header may either
* describe a string literal or a string reference.
*
* - string = 0x06 string-data
* - string-data = integer-data [ modified-utf-8 ]
* - modified-utf-8 = *OCTET
*
* @return String
*/
public function readString()
{
$stringReference = $this->readInteger();
//Check if this is a reference string
if (($stringReference & 0x01) == 0) {
// reference string
$stringReference = $stringReference >> 1;
if ($stringReference >= count($this->_referenceStrings)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Undefined string reference: ' . $stringReference);
}
// reference string found
return $this->_referenceStrings[$stringReference];
}
$length = $stringReference >> 1;
if ($length) {
$string = $this->_stream->readBytes($length);
$this->_referenceStrings[] = $string;
} else {
$string = "";
}
return $string;
}
/**
* Read and deserialize a date
*
* Data is the number of milliseconds elapsed since the epoch
* of midnight, 1st Jan 1970 in the UTC time zone.
* Local time zone information is not sent to flash.
*
* - date = 0x08 integer-data [ number-data ]
*
* @return Zend_Date
*/
public function readDate()
{
$dateReference = $this->readInteger();
if (($dateReference & 0x01) == 0) {
$dateReference = $dateReference >> 1;
if ($dateReference>=count($this->_referenceObjects)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Undefined date reference: ' . $dateReference);
}
return $this->_referenceObjects[$dateReference];
}
$timestamp = floor($this->_stream->readDouble() / 1000);
require_once 'Zend/Date.php';
$dateTime = new Zend_Date($timestamp);
$this->_referenceObjects[] = $dateTime;
return $dateTime;
}
/**
* Read amf array to PHP array
*
* - array = 0x09 integer-data ( [ 1OCTET *amf3-data ] | [OCTET *amf3-data 1] | [ OCTET *amf-data ] )
*
* @return array
*/
public function readArray()
{
$arrayReference = $this->readInteger();
if (($arrayReference & 0x01)==0){
$arrayReference = $arrayReference >> 1;
if ($arrayReference>=count($this->_referenceObjects)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknow array reference: ' . $arrayReference);
}
return $this->_referenceObjects[$arrayReference];
}
// Create a holder for the array in the reference list
$data = array();
$this->_referenceObjects[] =& $data;
$key = $this->readString();
// Iterating for string based keys.
while ($key != '') {
$data[$key] = $this->readTypeMarker();
$key = $this->readString();
}
$arrayReference = $arrayReference >>1;
//We have a dense array
for ($i=0; $i < $arrayReference; $i++) {
$data[] = $this->readTypeMarker();
}
return $data;
}
/**
* Read an object from the AMF stream and convert it into a PHP object
*
* @todo Rather than using an array of traitsInfo create Zend_Amf_Value_TraitsInfo
* @return object|array
*/
public function readObject()
{
$traitsInfo = $this->readInteger();
$storedObject = ($traitsInfo & 0x01)==0;
$traitsInfo = $traitsInfo >> 1;
// Check if the Object is in the stored Objects reference table
if ($storedObject) {
$ref = $traitsInfo;
if (!isset($this->_referenceObjects[$ref])) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Object reference: ' . $ref);
}
$returnObject = $this->_referenceObjects[$ref];
} else {
// Check if the Object is in the stored Definitions reference table
$storedClass = ($traitsInfo & 0x01) == 0;
$traitsInfo = $traitsInfo >> 1;
if ($storedClass) {
$ref = $traitsInfo;
if (!isset($this->_referenceDefinitions[$ref])) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknows Definition reference: '. $ref);
}
// Populate the reference attributes
$className = $this->_referenceDefinitions[$ref]['className'];
$encoding = $this->_referenceDefinitions[$ref]['encoding'];
$propertyNames = $this->_referenceDefinitions[$ref]['propertyNames'];
} else {
// The class was not in the reference tables. Start reading rawdata to build traits.
// Create a traits table. Zend_Amf_Value_TraitsInfo would be ideal
$className = $this->readString();
$encoding = $traitsInfo & 0x03;
$propertyNames = array();
$traitsInfo = $traitsInfo >> 2;
}
// We now have the object traits defined in variables. Time to go to work:
if (!$className) {
// No class name generic object
$returnObject = new stdClass();
} else {
// Defined object
// Typed object lookup against registered classname maps
if ($loader = Zend_Amf_Parse_TypeLoader::loadType($className)) {
$returnObject = new $loader();
} else {
//user defined typed object
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Typed object not found: '. $className . ' ');
}
}
// Add the Object to the reference table
$this->_referenceObjects[] = $returnObject;
$properties = array(); // clear value
// Check encoding types for additional processing.
switch ($encoding) {
case (Zend_Amf_Constants::ET_EXTERNAL):
// Externalizable object such as {ArrayCollection} and {ObjectProxy}
if (!$storedClass) {
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
$returnObject->externalizedData = $this->readTypeMarker();
break;
case (Zend_Amf_Constants::ET_DYNAMIC):
// used for Name-value encoding
if (!$storedClass) {
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
// not a reference object read name value properties from byte stream
do {
$property = $this->readString();
if ($property != "") {
$propertyNames[] = $property;
$properties[$property] = $this->readTypeMarker();
}
} while ($property !="");
break;
default:
// basic property list object.
if (!$storedClass) {
$count = $traitsInfo; // Number of properties in the list
for($i=0; $i< $count; $i++) {
$propertyNames[] = $this->readString();
}
// Add a reference to the class.
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
foreach ($propertyNames as $property) {
$properties[$property] = $this->readTypeMarker();
}
break;
}
// Add properties back to the return object.
foreach($properties as $key=>$value) {
if($key) {
$returnObject->$key = $value;
}
}
}
if ($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) {
if (isset($returnObject->externalizedData)) {
$returnObject = $returnObject->externalizedData;
} else {
$returnObject = get_object_vars($returnObject);
}
}
return $returnObject;
}
/**
* Convert XML to SimpleXml
* If user wants DomDocument they can use dom_import_simplexml
*
* @return SimpleXml Object
*/
public function readXmlString()
{
$xmlReference = $this->readInteger();
$length = $xmlReference >> 1;
$string = $this->_stream->readBytes($length);
return simplexml_load_string($string);
}
}

View File

@ -1,534 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse_Amf3
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Serializer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** Zend_Amf_Parse_Serializer */
require_once 'Zend/Amf/Parse/Serializer.php';
/** Zend_Amf_Parse_TypeLoader */
require_once 'Zend/Amf/Parse/TypeLoader.php';
/**
* Detect PHP object type and convert it to a corresponding AMF3 object type
*
* @package Zend_Amf
* @subpackage Parse_Amf3
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Amf3_Serializer extends Zend_Amf_Parse_Serializer
{
/**
* A constant empty string
* @var string
*/
protected $_strEmpty = '';
/**
* An array of reference objects per amf body
* @var array
*/
protected $_referenceObjects = array();
/**
* An array of reference strings per amf body
* @var array
*/
protected $_referenceStrings = array();
/**
* An array of reference class definitions, indexed by classname
* @var array
*/
protected $_referenceDefinitions = array();
/**
* Serialize PHP types to AMF3 and write to stream
*
* Checks to see if the type was declared and then either
* auto negotiates the type or use the user defined markerType to
* serialize the data from php back to AMF3
*
* @param mixed $data
* @param int $markerType
* @param mixed $dataByVal
* @return void
*/
public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $data) && ($dataByVal !== false)) {
$data = &$dataByVal;
}
if (null !== $markerType) {
// Write the Type Marker to denote the following action script data type
$this->_stream->writeByte($markerType);
switch ($markerType) {
case Zend_Amf_Constants::AMF3_NULL:
break;
case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE:
break;
case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE:
break;
case Zend_Amf_Constants::AMF3_INTEGER:
$this->writeInteger($data);
break;
case Zend_Amf_Constants::AMF3_NUMBER:
$this->_stream->writeDouble($data);
break;
case Zend_Amf_Constants::AMF3_STRING:
$this->writeString($data);
break;
case Zend_Amf_Constants::AMF3_DATE:
$this->writeDate($data);
break;
case Zend_Amf_Constants::AMF3_ARRAY:
$this->writeArray($data);
break;
case Zend_Amf_Constants::AMF3_OBJECT:
$this->writeObject($data);
break;
case Zend_Amf_Constants::AMF3_BYTEARRAY:
$this->writeByteArray($data);
break;
case Zend_Amf_Constants::AMF3_XMLSTRING;
$this->writeXml($data);
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Type Marker: ' . $markerType);
}
} else {
// Detect Type Marker
if (is_resource($data)) {
$data = Zend_Amf_Parse_TypeLoader::handleResource($data);
}
switch (true) {
case (null === $data):
$markerType = Zend_Amf_Constants::AMF3_NULL;
break;
case (is_bool($data)):
if ($data){
$markerType = Zend_Amf_Constants::AMF3_BOOLEAN_TRUE;
} else {
$markerType = Zend_Amf_Constants::AMF3_BOOLEAN_FALSE;
}
break;
case (is_int($data)):
if (($data > 0xFFFFFFF) || ($data < -268435456)) {
$markerType = Zend_Amf_Constants::AMF3_NUMBER;
} else {
$markerType = Zend_Amf_Constants::AMF3_INTEGER;
}
break;
case (is_float($data)):
$markerType = Zend_Amf_Constants::AMF3_NUMBER;
break;
case (is_string($data)):
$markerType = Zend_Amf_Constants::AMF3_STRING;
break;
case (is_array($data)):
$markerType = Zend_Amf_Constants::AMF3_ARRAY;
break;
case (is_object($data)):
// Handle object types.
if (($data instanceof DateTime) || ($data instanceof Zend_Date)) {
$markerType = Zend_Amf_Constants::AMF3_DATE;
} else if ($data instanceof Zend_Amf_Value_ByteArray) {
$markerType = Zend_Amf_Constants::AMF3_BYTEARRAY;
} else if (($data instanceof DOMDocument) || ($data instanceof SimpleXMLElement)) {
$markerType = Zend_Amf_Constants::AMF3_XMLSTRING;
} else {
$markerType = Zend_Amf_Constants::AMF3_OBJECT;
}
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data));
}
$this->writeTypeMarker($data, $markerType);
}
}
/**
* Write an AMF3 integer
*
* @param int|float $data
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeInteger($int)
{
if (($int & 0xffffff80) == 0) {
$this->_stream->writeByte($int & 0x7f);
return $this;
}
if (($int & 0xffffc000) == 0 ) {
$this->_stream->writeByte(($int >> 7 ) | 0x80);
$this->_stream->writeByte($int & 0x7f);
return $this;
}
if (($int & 0xffe00000) == 0) {
$this->_stream->writeByte(($int >> 14 ) | 0x80);
$this->_stream->writeByte(($int >> 7 ) | 0x80);
$this->_stream->writeByte($int & 0x7f);
return $this;
}
$this->_stream->writeByte(($int >> 22 ) | 0x80);
$this->_stream->writeByte(($int >> 15 ) | 0x80);
$this->_stream->writeByte(($int >> 8 ) | 0x80);
$this->_stream->writeByte($int & 0xff);
return $this;
}
/**
* Send string to output stream, without trying to reference it.
* The string is prepended with strlen($string) << 1 | 0x01
*
* @param string $string
* @return Zend_Amf_Parse_Amf3_Serializer
*/
protected function writeBinaryString(&$string){
$ref = strlen($string) << 1 | 0x01;
$this->writeInteger($ref);
$this->_stream->writeBytes($string);
return $this;
}
/**
* Send string to output stream
*
* @param string $string
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeString(&$string)
{
$len = strlen($string);
if(!$len){
$this->writeInteger(0x01);
return $this;
}
$ref = array_key_exists($string, $this->_referenceStrings)
? $this->_referenceStrings[$string]
: false;
if ($ref === false){
$this->_referenceStrings[$string] = count($this->_referenceStrings);
$this->writeBinaryString($string);
} else {
$ref <<= 1;
$this->writeInteger($ref);
}
return $this;
}
/**
* Send ByteArray to output stream
*
* @param string|Zend_Amf_Value_ByteArray $data
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeByteArray(&$data)
{
if ($this->writeObjectReference($data)) {
return $this;
}
if (is_string($data)) {
//nothing to do
} else if ($data instanceof Zend_Amf_Value_ByteArray) {
$data = $data->getData();
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid ByteArray specified; must be a string or Zend_Amf_Value_ByteArray');
}
$this->writeBinaryString($data);
return $this;
}
/**
* Send xml to output stream
*
* @param DOMDocument|SimpleXMLElement $xml
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeXml($xml)
{
if ($this->writeObjectReference($xml)) {
return $this;
}
if(is_string($xml)) {
//nothing to do
} else if ($xml instanceof DOMDocument) {
$xml = $xml->saveXml();
} else if ($xml instanceof SimpleXMLElement) {
$xml = $xml->asXML();
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid xml specified; must be a DOMDocument or SimpleXMLElement');
}
$this->writeBinaryString($xml);
return $this;
}
/**
* Convert DateTime/Zend_Date to AMF date
*
* @param DateTime|Zend_Date $date
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeDate($date)
{
if ($this->writeObjectReference($date)) {
return $this;
}
if ($date instanceof DateTime) {
$dateString = $date->format('U') * 1000;
} elseif ($date instanceof Zend_Date) {
$dateString = $date->toString('U') * 1000;
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid date specified; must be a string DateTime or Zend_Date object');
}
$this->writeInteger(0x01);
// write time to stream minus milliseconds
$this->_stream->writeDouble($dateString);
return $this;
}
/**
* Write a PHP array back to the amf output stream
*
* @param array $array
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeArray(&$array)
{
// arrays aren't reference here but still counted
$this->_referenceObjects[] = $array;
// have to seperate mixed from numberic keys.
$numeric = array();
$string = array();
foreach ($array as $key => &$value) {
if (is_int($key)) {
$numeric[] = $value;
} else {
$string[$key] = $value;
}
}
// write the preamble id of the array
$length = count($numeric);
$id = ($length << 1) | 0x01;
$this->writeInteger($id);
//Write the mixed type array to the output stream
foreach($string as $key => &$value) {
$this->writeString($key)
->writeTypeMarker($value);
}
$this->writeString($this->_strEmpty);
// Write the numeric array to ouput stream
foreach($numeric as &$value) {
$this->writeTypeMarker($value);
}
return $this;
}
/**
* Check if the given object is in the reference table, write the reference if it exists,
* otherwise add the object to the reference table
*
* @param mixed $object object reference to check for reference
* @param mixed $objectByVal object to check for reference
* @return Boolean true, if the reference was written, false otherwise
*/
protected function writeObjectReference(&$object, $objectByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $object) && ($objectByVal !== false)) {
$object = &$objectByVal;
}
$hash = spl_object_hash($object);
$ref = array_key_exists($hash, $this->_referenceObjects)
? $this->_referenceObjects[$hash]
: false;
// quickly handle object references
if ($ref !== false){
$ref <<= 1;
$this->writeInteger($ref);
return true;
}
$this->_referenceObjects[$hash] = count($this->_referenceObjects);
return false;
}
/**
* Write object to ouput stream
*
* @param mixed $data
* @return Zend_Amf_Parse_Amf3_Serializer
*/
public function writeObject($object)
{
if($this->writeObjectReference($object)){
return $this;
}
$className = '';
//Check to see if the object is a typed object and we need to change
switch (true) {
// the return class mapped name back to actionscript class name.
case ($className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object))):
break;
// Check to see if the user has defined an explicit Action Script type.
case isset($object->_explicitType):
$className = $object->_explicitType;
break;
// Check if user has defined a method for accessing the Action Script type
case method_exists($object, 'getASClassName'):
$className = $object->getASClassName();
break;
// No return class name is set make it a generic object
case ($object instanceof stdClass):
$className = '';
break;
// By default, use object's class name
default:
$className = get_class($object);
break;
}
$writeTraits = true;
//check to see, if we have a corresponding definition
if(array_key_exists($className, $this->_referenceDefinitions)){
$traitsInfo = $this->_referenceDefinitions[$className]['id'];
$encoding = $this->_referenceDefinitions[$className]['encoding'];
$propertyNames = $this->_referenceDefinitions[$className]['propertyNames'];
$traitsInfo = ($traitsInfo << 2) | 0x01;
$writeTraits = false;
} else {
$propertyNames = array();
if($className == ''){
//if there is no className, we interpret the class as dynamic without any sealed members
$encoding = Zend_Amf_Constants::ET_DYNAMIC;
} else {
$encoding = Zend_Amf_Constants::ET_PROPLIST;
foreach($object as $key => $value) {
if( $key[0] != "_") {
$propertyNames[] = $key;
}
}
}
$this->_referenceDefinitions[$className] = array(
'id' => count($this->_referenceDefinitions),
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
$traitsInfo = Zend_Amf_Constants::AMF3_OBJECT_ENCODING;
$traitsInfo |= $encoding << 2;
$traitsInfo |= (count($propertyNames) << 4);
}
$this->writeInteger($traitsInfo);
if($writeTraits){
$this->writeString($className);
foreach ($propertyNames as $value) {
$this->writeString($value);
}
}
try {
switch($encoding) {
case Zend_Amf_Constants::ET_PROPLIST:
//Write the sealed values to the output stream.
foreach ($propertyNames as $key) {
$this->writeTypeMarker($object->$key);
}
break;
case Zend_Amf_Constants::ET_DYNAMIC:
//Write the sealed values to the output stream.
foreach ($propertyNames as $key) {
$this->writeTypeMarker($object->$key);
}
//Write remaining properties
foreach($object as $key => $value){
if(!in_array($key,$propertyNames) && $key[0] != "_"){
$this->writeString($key);
$this->writeTypeMarker($value);
}
}
//Write an empty string to end the dynamic part
$this->writeString($this->_strEmpty);
break;
case Zend_Amf_Constants::ET_EXTERNAL:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('External Object Encoding not implemented');
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Object Encoding type: ' . $encoding);
}
} catch (Exception $e) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unable to writeObject output: ' . $e->getMessage(), 0, $e);
}
return $this;
}
}

View File

@ -1,65 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Deserializer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Abstract cass that all deserializer must implement.
*
* Logic for deserialization of the AMF envelop is based on resources supplied
* by Adobe Blaze DS. For and example of deserialization please review the BlazeDS
* source tree.
*
* @see http://opensource.adobe.com/svn/opensource/blazeds/trunk/modules/core/src/java/flex/messaging/io/amf/
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Amf_Parse_Deserializer
{
/**
* The raw string that represents the AMF request.
*
* @var Zend_Amf_Parse_InputStream
*/
protected $_stream;
/**
* Constructor
*
* @param Zend_Amf_Parse_InputStream $stream
* @return void
*/
public function __construct(Zend_Amf_Parse_InputStream $stream)
{
$this->_stream = $stream;
}
/**
* Checks for AMF marker types and calls the appropriate methods
* for deserializing those marker types. Markers are the data type of
* the following value.
*
* @param int $typeMarker
* @return mixed Whatever the data type is of the marker in php
*/
public abstract function readTypeMarker($markerType = null);
}

View File

@ -1,39 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: InputStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Util_BinaryStream */
require_once 'Zend/Amf/Util/BinaryStream.php';
/**
* InputStream is used to iterate at a binary level through the AMF request.
*
* InputStream extends BinaryStream as eventually BinaryStream could be placed
* outside of Zend_Amf in order to allow other packages to use the class.
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_InputStream extends Zend_Amf_Util_BinaryStream
{
}

View File

@ -1,49 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: OutputStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Util_BinaryStream */
require_once 'Zend/Amf/Util/BinaryStream.php';
/**
* Iterate at a binary level through the AMF response
*
* OutputStream extends BinaryStream as eventually BinaryStream could be placed
* outside of Zend_Amf in order to allow other packages to use the class.
*
* @uses Zend_Amf_Util_BinaryStream
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_OutputStream extends Zend_Amf_Util_BinaryStream
{
/**
* Constructor
*
* @return void
*/
public function __construct()
{
parent::__construct('');
}
}

View File

@ -1,70 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MysqlResult.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This class will convert mysql result resource to array suitable for passing
* to the external entities.
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Resource_MysqlResult
{
/**
* @var array List of Mysql types with PHP counterparts
*
* Key => Value is Mysql type (exact string) => PHP type
*/
static public $fieldTypes = array(
"int" => "int",
"timestamp" => "int",
"year" => "int",
"real" => "float",
);
/**
* Parse resource into array
*
* @param resource $resource
* @return array
*/
public function parse($resource) {
$result = array();
$fieldcnt = mysql_num_fields($resource);
$fields_transform = array();
for($i=0;$i<$fieldcnt;$i++) {
$type = mysql_field_type($resource, $i);
if(isset(self::$fieldTypes[$type])) {
$fields_transform[mysql_field_name($resource, $i)] = self::$fieldTypes[$type];
}
}
while($row = mysql_fetch_object($resource)) {
foreach($fields_transform as $fieldname => $fieldtype) {
settype($row->$fieldname, $fieldtype);
}
$result[] = $row;
}
return $result;
}
}

View File

@ -1,128 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MysqliResult.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This class will convert mysql result resource to array suitable for passing
* to the external entities.
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Resource_MysqliResult
{
/**
* mapping taken from http://forums.mysql.com/read.php?52,255868,255895#msg-255895
*/
static public $mysqli_type = array(
0 => "MYSQLI_TYPE_DECIMAL",
1 => "MYSQLI_TYPE_TINYINT",
2 => "MYSQLI_TYPE_SMALLINT",
3 => "MYSQLI_TYPE_INTEGER",
4 => "MYSQLI_TYPE_FLOAT",
5 => "MYSQLI_TYPE_DOUBLE",
7 => "MYSQLI_TYPE_TIMESTAMP",
8 => "MYSQLI_TYPE_BIGINT",
9 => "MYSQLI_TYPE_MEDIUMINT",
10 => "MYSQLI_TYPE_DATE",
11 => "MYSQLI_TYPE_TIME",
12 => "MYSQLI_TYPE_DATETIME",
13 => "MYSQLI_TYPE_YEAR",
14 => "MYSQLI_TYPE_DATE",
16 => "MYSQLI_TYPE_BIT",
246 => "MYSQLI_TYPE_DECIMAL",
247 => "MYSQLI_TYPE_ENUM",
248 => "MYSQLI_TYPE_SET",
249 => "MYSQLI_TYPE_TINYBLOB",
250 => "MYSQLI_TYPE_MEDIUMBLOB",
251 => "MYSQLI_TYPE_LONGBLOB",
252 => "MYSQLI_TYPE_BLOB",
253 => "MYSQLI_TYPE_VARCHAR",
254 => "MYSQLI_TYPE_CHAR",
255 => "MYSQLI_TYPE_GEOMETRY",
);
// Build an associative array for a type look up
static $mysqli_to_php = array(
"MYSQLI_TYPE_DECIMAL" => 'float',
"MYSQLI_TYPE_NEWDECIMAL" => 'float',
"MYSQLI_TYPE_BIT" => 'integer',
"MYSQLI_TYPE_TINYINT" => 'integer',
"MYSQLI_TYPE_SMALLINT" => 'integer',
"MYSQLI_TYPE_MEDIUMINT" => 'integer',
"MYSQLI_TYPE_BIGINT" => 'integer',
"MYSQLI_TYPE_INTEGER" => 'integer',
"MYSQLI_TYPE_FLOAT" => 'float',
"MYSQLI_TYPE_DOUBLE" => 'float',
"MYSQLI_TYPE_NULL" => 'null',
"MYSQLI_TYPE_TIMESTAMP" => 'string',
"MYSQLI_TYPE_INT24" => 'integer',
"MYSQLI_TYPE_DATE" => 'string',
"MYSQLI_TYPE_TIME" => 'string',
"MYSQLI_TYPE_DATETIME" => 'string',
"MYSQLI_TYPE_YEAR" => 'string',
"MYSQLI_TYPE_NEWDATE" => 'string',
"MYSQLI_TYPE_ENUM" => 'string',
"MYSQLI_TYPE_SET" => 'string',
"MYSQLI_TYPE_TINYBLOB" => 'object',
"MYSQLI_TYPE_MEDIUMBLOB" => 'object',
"MYSQLI_TYPE_LONGBLOB" => 'object',
"MYSQLI_TYPE_BLOB" => 'object',
"MYSQLI_TYPE_CHAR" => 'string',
"MYSQLI_TYPE_VARCHAR" => 'string',
"MYSQLI_TYPE_GEOMETRY" => 'object',
"MYSQLI_TYPE_BIT" => 'integer',
);
/**
* Parse resource into array
*
* @param resource $resource
* @return array
*/
public function parse($resource) {
$result = array();
$fieldcnt = mysqli_num_fields($resource);
$fields_transform = array();
for($i=0;$i<$fieldcnt;$i++) {
$finfo = mysqli_fetch_field_direct($resource, $i);
if(isset(self::$mysqli_type[$finfo->type])) {
$fields_transform[$finfo->name] = self::$mysqli_to_php[self::$mysqli_type[$finfo->type]];
}
}
while($row = mysqli_fetch_assoc($resource)) {
foreach($fields_transform as $fieldname => $fieldtype) {
settype($row[$fieldname], $fieldtype);
}
$result[] = $row;
}
return $result;
}
}

View File

@ -1,42 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Stream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This class will convert stream resource to string by just reading it
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Parse_Resource_Stream
{
/**
* Parse resource into string
*
* @param resource $resource Stream resource
* @return array
*/
public function parse($resource) {
return stream_get_contents($resource);
}
}

View File

@ -1,60 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Serializer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Base abstract class for all AMF serializers.
*
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Amf_Parse_Serializer
{
/**
* Reference to the current output stream being constructed
*
* @var string
*/
protected $_stream;
/**
* Constructor
*
* @param Zend_Amf_Parse_OutputStream $stream
* @return void
*/
public function __construct(Zend_Amf_Parse_OutputStream $stream)
{
$this->_stream = $stream;
}
/**
* Find the PHP object type and convert it into an AMF object type
*
* @param mixed $content
* @param int $markerType
* @param mixed $contentByVal
* @return void
*/
public abstract function writeTypeMarker(&$content, $markerType = null, $contentByVal = false);
}

View File

@ -1,231 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TypeLoader.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Amf_Value_Messaging_AcknowledgeMessage
*/
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
/**
* @see Zend_Amf_Value_Messaging_AsyncMessage
*/
require_once 'Zend/Amf/Value/Messaging/AsyncMessage.php';
/**
* @see Zend_Amf_Value_Messaging_CommandMessage
*/
require_once 'Zend/Amf/Value/Messaging/CommandMessage.php';
/**
* @see Zend_Amf_Value_Messaging_ErrorMessage
*/
require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
/**
* @see Zend_Amf_Value_Messaging_RemotingMessage
*/
require_once 'Zend/Amf/Value/Messaging/RemotingMessage.php';
/**
* Loads a local class and executes the instantiation of that class.
*
* @todo PHP 5.3 can drastically change this class w/ namespace and the new call_user_func w/ namespace
* @package Zend_Amf
* @subpackage Parse
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
final class Zend_Amf_Parse_TypeLoader
{
/**
* @var string callback class
*/
public static $callbackClass;
/**
* @var array AMF class map
*/
public static $classMap = array (
'flex.messaging.messages.AcknowledgeMessage' => 'Zend_Amf_Value_Messaging_AcknowledgeMessage',
'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_AsyncMessage',
'flex.messaging.messages.CommandMessage' => 'Zend_Amf_Value_Messaging_CommandMessage',
'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_ErrorMessage',
'flex.messaging.messages.RemotingMessage' => 'Zend_Amf_Value_Messaging_RemotingMessage',
'flex.messaging.io.ArrayCollection' => 'Zend_Amf_Value_Messaging_ArrayCollection',
);
/**
* @var array Default class map
*/
protected static $_defaultClassMap = array(
'flex.messaging.messages.AcknowledgeMessage' => 'Zend_Amf_Value_Messaging_AcknowledgeMessage',
'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_AsyncMessage',
'flex.messaging.messages.CommandMessage' => 'Zend_Amf_Value_Messaging_CommandMessage',
'flex.messaging.messages.ErrorMessage' => 'Zend_Amf_Value_Messaging_ErrorMessage',
'flex.messaging.messages.RemotingMessage' => 'Zend_Amf_Value_Messaging_RemotingMessage',
'flex.messaging.io.ArrayCollection' => 'Zend_Amf_Value_Messaging_ArrayCollection',
);
/**
* @var Zend_Loader_PluginLoader_Interface
*/
protected static $_resourceLoader = null;
/**
* Load the mapped class type into a callback.
*
* @param string $className
* @return object|false
*/
public static function loadType($className)
{
$class = self::getMappedClassName($className);
if(!$class) {
$class = str_replace('.', '_', $className);
}
if (!class_exists($class)) {
return "stdClass";
}
return $class;
}
/**
* Looks up the supplied call name to its mapped class name
*
* @param string $className
* @return string
*/
public static function getMappedClassName($className)
{
$mappedName = array_search($className, self::$classMap);
if ($mappedName) {
return $mappedName;
}
$mappedName = array_search($className, array_flip(self::$classMap));
if ($mappedName) {
return $mappedName;
}
return false;
}
/**
* Map PHP class names to ActionScript class names
*
* Allows users to map the class names of there action script classes
* to the equivelent php class name. Used in deserialization to load a class
* and serialiation to set the class name of the returned object.
*
* @param string $asClassName
* @param string $phpClassName
* @return void
*/
public static function setMapping($asClassName, $phpClassName)
{
self::$classMap[$asClassName] = $phpClassName;
}
/**
* Reset type map
*
* @return void
*/
public static function resetMap()
{
self::$classMap = self::$_defaultClassMap;
}
/**
* Set loader for resource type handlers
*
* @param Zend_Loader_PluginLoader_Interface $loader
*/
public static function setResourceLoader(Zend_Loader_PluginLoader_Interface $loader)
{
self::$_resourceLoader = $loader;
}
/**
* Add directory to the list of places where to look for resource handlers
*
* @param string $prefix
* @param string $dir
*/
public static function addResourceDirectory($prefix, $dir)
{
if(self::$_resourceLoader) {
self::$_resourceLoader->addPrefixPath($prefix, $dir);
}
}
/**
* Get plugin class that handles this resource
*
* @param resource $resource Resource type
* @return string Class name
*/
public static function getResourceParser($resource)
{
if(self::$_resourceLoader) {
$type = preg_replace("/[^A-Za-z0-9_]/", " ", get_resource_type($resource));
$type = str_replace(" ","", ucwords($type));
return self::$_resourceLoader->load($type);
}
return false;
}
/**
* Convert resource to a serializable object
*
* @param resource $resource
* @return mixed
*/
public static function handleResource($resource)
{
if(!self::$_resourceLoader) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unable to handle resources - resource plugin loader not set');
}
try {
while(is_resource($resource)) {
$resclass = self::getResourceParser($resource);
if(!$resclass) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource));
}
$parser = new $resclass();
if(is_callable(array($parser, 'parse'))) {
$resource = $parser->parse($resource);
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception("Could not call parse() method on class $resclass");
}
}
return $resource;
} catch(Zend_Amf_Exception $e) {
throw new Zend_Amf_Exception($e->getMessage(), $e->getCode(), $e);
} catch(Exception $e) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource), 0, $e);
}
}
}

View File

@ -1,251 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Request.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Amf_Parse_InputStream */
require_once 'Zend/Amf/Parse/InputStream.php';
/** @see Zend_Amf_Parse_Amf0_Deserializer */
require_once 'Zend/Amf/Parse/Amf0/Deserializer.php';
/** @see Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** @see Zend_Amf_Value_MessageHeader */
require_once 'Zend/Amf/Value/MessageHeader.php';
/** @see Zend_Amf_Value_MessageBody */
require_once 'Zend/Amf/Value/MessageBody.php';
/**
* Handle the incoming AMF request by deserializing the data to php object
* types and storing the data for Zend_Amf_Server to handle for processing.
*
* @todo Currently not checking if the object needs to be Type Mapped to a server object.
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Request
{
/**
* @var int AMF client type (AMF0, AMF3)
*/
protected $_clientType = 0; // default AMF0
/**
* @var array Message bodies
*/
protected $_bodies = array();
/**
* @var array Message headers
*/
protected $_headers = array();
/**
* @var int Message encoding to use for objects in response
*/
protected $_objectEncoding = 0;
/**
* @var Zend_Amf_Parse_InputStream
*/
protected $_inputStream;
/**
* @var Zend_Amf_Parse_AMF0_Deserializer
*/
protected $_deserializer;
/**
* Time of the request
* @var mixed
*/
protected $_time;
/**
* Prepare the AMF InputStream for parsing.
*
* @param string $request
* @return Zend_Amf_Request
*/
public function initialize($request)
{
$this->_inputStream = new Zend_Amf_Parse_InputStream($request);
$this->_deserializer = new Zend_Amf_Parse_Amf0_Deserializer($this->_inputStream);
$this->readMessage($this->_inputStream);
return $this;
}
/**
* Takes the raw AMF input stream and converts it into valid PHP objects
*
* @param Zend_Amf_Parse_InputStream
* @return Zend_Amf_Request
*/
public function readMessage(Zend_Amf_Parse_InputStream $stream)
{
$clientVersion = $stream->readUnsignedShort();
if (($clientVersion != Zend_Amf_Constants::AMF0_OBJECT_ENCODING)
&& ($clientVersion != Zend_Amf_Constants::AMF3_OBJECT_ENCODING)
&& ($clientVersion != Zend_Amf_Constants::FMS_OBJECT_ENCODING)
) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Player Version ' . $clientVersion);
}
$this->_bodies = array();
$this->_headers = array();
$headerCount = $stream->readInt();
// Iterate through the AMF envelope header
while ($headerCount--) {
$this->_headers[] = $this->readHeader();
}
// Iterate through the AMF envelope body
$bodyCount = $stream->readInt();
while ($bodyCount--) {
$this->_bodies[] = $this->readBody();
}
return $this;
}
/**
* Deserialize a message header from the input stream.
*
* A message header is structured as:
* - NAME String
* - MUST UNDERSTAND Boolean
* - LENGTH Int
* - DATA Object
*
* @return Zend_Amf_Value_MessageHeader
*/
public function readHeader()
{
$name = $this->_inputStream->readUTF();
$mustRead = (bool)$this->_inputStream->readByte();
$length = $this->_inputStream->readLong();
try {
$data = $this->_deserializer->readTypeMarker();
} catch (Exception $e) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unable to parse ' . $name . ' header data: ' . $e->getMessage() . ' '. $e->getLine(), 0, $e);
}
$header = new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length);
return $header;
}
/**
* Deserialize a message body from the input stream
*
* @return Zend_Amf_Value_MessageBody
*/
public function readBody()
{
$targetURI = $this->_inputStream->readUTF();
$responseURI = $this->_inputStream->readUTF();
$length = $this->_inputStream->readLong();
try {
$data = $this->_deserializer->readTypeMarker();
} catch (Exception $e) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unable to parse ' . $targetURI . ' body data ' . $e->getMessage(), 0, $e);
}
// Check for AMF3 objectEncoding
if ($this->_deserializer->getObjectEncoding() == Zend_Amf_Constants::AMF3_OBJECT_ENCODING) {
/*
* When and AMF3 message is sent to the server it is nested inside
* an AMF0 array called Content. The following code gets the object
* out of the content array and sets it as the message data.
*/
if(is_array($data) && $data[0] instanceof Zend_Amf_Value_Messaging_AbstractMessage){
$data = $data[0];
}
// set the encoding so we return our message in AMF3
$this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING;
}
$body = new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data);
return $body;
}
/**
* Return an array of the body objects that were found in the amf request.
*
* @return array {target, response, length, content}
*/
public function getAmfBodies()
{
return $this->_bodies;
}
/**
* Accessor to private array of message bodies.
*
* @param Zend_Amf_Value_MessageBody $message
* @return Zend_Amf_Request
*/
public function addAmfBody(Zend_Amf_Value_MessageBody $message)
{
$this->_bodies[] = $message;
return $this;
}
/**
* Return an array of headers that were found in the amf request.
*
* @return array {operation, mustUnderstand, length, param}
*/
public function getAmfHeaders()
{
return $this->_headers;
}
/**
* Return the either 0 or 3 for respect AMF version
*
* @return int
*/
public function getObjectEncoding()
{
return $this->_objectEncoding;
}
/**
* Set the object response encoding
*
* @param mixed $int
* @return Zend_Amf_Request
*/
public function setObjectEncoding($int)
{
$this->_objectEncoding = $int;
return $this;
}
}

View File

@ -1,80 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Request
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Http.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Amf_Request */
require_once 'Zend/Amf/Request.php';
/**
* AMF Request object -- Request via HTTP
*
* Extends {@link Zend_Amf_Request} to accept a request via HTTP. Request is
* built at construction time using a raw POST; if no data is available, the
* request is declared a fault.
*
* @package Zend_Amf
* @subpackage Request
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Request_Http extends Zend_Amf_Request
{
/**
* Raw AMF request
* @var string
*/
protected $_rawRequest;
/**
* Constructor
*
* Attempts to read from php://input to get raw POST request; if an error
* occurs in doing so, or if the AMF body is invalid, the request is declared a
* fault.
*
* @return void
*/
public function __construct()
{
// php://input allows you to read raw POST data. It is a less memory
// intensive alternative to $HTTP_RAW_POST_DATA and does not need any
// special php.ini directives
$amfRequest = file_get_contents('php://input');
// Check to make sure that we have data on the input stream.
if ($amfRequest != '') {
$this->_rawRequest = $amfRequest;
$this->initialize($amfRequest);
} else {
echo '<p>Zend Amf Endpoint</p>' ;
}
}
/**
* Retrieve raw AMF Request
*
* @return string
*/
public function getRawRequest()
{
return $this->_rawRequest;
}
}

View File

@ -1,205 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Response.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** @see Zend_Amf_Parse_OutputStream */
require_once 'Zend/Amf/Parse/OutputStream.php';
/** @see Zend_Amf_Parse_Amf0_Serializer */
require_once 'Zend/Amf/Parse/Amf0/Serializer.php';
/**
* Handles converting the PHP object ready for response back into AMF
*
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Response
{
/**
* @var int Object encoding for response
*/
protected $_objectEncoding = 0;
/**
* Array of Zend_Amf_Value_MessageBody objects
* @var array
*/
protected $_bodies = array();
/**
* Array of Zend_Amf_Value_MessageHeader objects
* @var array
*/
protected $_headers = array();
/**
* @var Zend_Amf_Parse_OutputStream
*/
protected $_outputStream;
/**
* Instantiate new output stream and start serialization
*
* @return Zend_Amf_Response
*/
public function finalize()
{
$this->_outputStream = new Zend_Amf_Parse_OutputStream();
$this->writeMessage($this->_outputStream);
return $this;
}
/**
* Serialize the PHP data types back into Actionscript and
* create and AMF stream.
*
* @param Zend_Amf_Parse_OutputStream $stream
* @return Zend_Amf_Response
*/
public function writeMessage(Zend_Amf_Parse_OutputStream $stream)
{
$objectEncoding = $this->_objectEncoding;
//Write encoding to start of stream. Preamble byte is written of two byte Unsigned Short
$stream->writeByte(0x00);
$stream->writeByte($objectEncoding);
// Loop through the AMF Headers that need to be returned.
$headerCount = count($this->_headers);
$stream->writeInt($headerCount);
foreach ($this->getAmfHeaders() as $header) {
$serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
$stream->writeUTF($header->name);
$stream->writeByte($header->mustRead);
$stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
if (is_object($header->data)) {
// Workaround for PHP5 with E_STRICT enabled complaining about
// "Only variables should be passed by reference"
$placeholder = null;
$serializer->writeTypeMarker($placeholder, null, $header->data);
} else {
$serializer->writeTypeMarker($header->data);
}
}
// loop through the AMF bodies that need to be returned.
$bodyCount = count($this->_bodies);
$stream->writeInt($bodyCount);
foreach ($this->_bodies as $body) {
$serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
$stream->writeUTF($body->getTargetURI());
$stream->writeUTF($body->getResponseURI());
$stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
$bodyData = $body->getData();
$markerType = ($this->_objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) ? null : Zend_Amf_Constants::AMF0_AMF3;
if (is_object($bodyData)) {
// Workaround for PHP5 with E_STRICT enabled complaining about
// "Only variables should be passed by reference"
$placeholder = null;
$serializer->writeTypeMarker($placeholder, $markerType, $bodyData);
} else {
$serializer->writeTypeMarker($bodyData, $markerType);
}
}
return $this;
}
/**
* Return the output stream content
*
* @return string The contents of the output stream
*/
public function getResponse()
{
return $this->_outputStream->getStream();
}
/**
* Return the output stream content
*
* @return string
*/
public function __toString()
{
return $this->getResponse();
}
/**
* Add an AMF body to be sent to the Flash Player
*
* @param Zend_Amf_Value_MessageBody $body
* @return Zend_Amf_Response
*/
public function addAmfBody(Zend_Amf_Value_MessageBody $body)
{
$this->_bodies[] = $body;
return $this;
}
/**
* Return an array of AMF bodies to be serialized
*
* @return array
*/
public function getAmfBodies()
{
return $this->_bodies;
}
/**
* Add an AMF Header to be sent back to the flash player
*
* @param Zend_Amf_Value_MessageHeader $header
* @return Zend_Amf_Response
*/
public function addAmfHeader(Zend_Amf_Value_MessageHeader $header)
{
$this->_headers[] = $header;
return $this;
}
/**
* Retrieve attached AMF message headers
*
* @return array Array of Zend_Amf_Value_MessageHeader objects
*/
public function getAmfHeaders()
{
return $this->_headers;
}
/**
* Set the AMF encoding that will be used for serialization
*
* @param int $encoding
* @return Zend_Amf_Response
*/
public function setObjectEncoding($encoding)
{
$this->_objectEncoding = $encoding;
return $this;
}
}

View File

@ -1,51 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Response
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Http.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Response */
require_once 'Zend/Amf/Response.php';
/**
* Creates the proper http headers and send the serialized AMF stream to standard out.
*
* @package Zend_Amf
* @subpackage Response
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Response_Http extends Zend_Amf_Response
{
/**
* Create the application response header for AMF and sends the serialized AMF string
*
* @return string
*/
public function getResponse()
{
if (!headers_sent()) {
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
header('Pragma: no-cache');
header('Content-Type: application/x-amf');
}
return parent::getResponse();
}
}

View File

@ -1,964 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Server.php 24206 2011-07-06 13:52:02Z matthew $
*/
/** @see Zend_Server_Interface */
require_once 'Zend/Server/Interface.php';
/** @see Zend_Server_Reflection */
require_once 'Zend/Server/Reflection.php';
/** @see Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';
/** @see Zend_Amf_Value_MessageBody */
require_once 'Zend/Amf/Value/MessageBody.php';
/** @see Zend_Amf_Value_MessageHeader */
require_once 'Zend/Amf/Value/MessageHeader.php';
/** @see Zend_Amf_Value_Messaging_CommandMessage */
require_once 'Zend/Amf/Value/Messaging/CommandMessage.php';
/** @see Zend_Loader_PluginLoader */
require_once 'Zend/Loader/PluginLoader.php';
/** @see Zend_Amf_Parse_TypeLoader */
require_once 'Zend/Amf/Parse/TypeLoader.php';
/** @see Zend_Auth */
require_once 'Zend/Auth.php';
/**
* An AMF gateway server implementation to allow the connection of the Adobe Flash Player to
* Zend Framework
*
* @todo Make the reflection methods cache and autoload.
* @package Zend_Amf
* @subpackage Server
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Server implements Zend_Server_Interface
{
/**
* Array of dispatchables
* @var array
*/
protected $_methods = array();
/**
* Array of classes that can be called without being explicitly loaded
*
* Keys are class names.
*
* @var array
*/
protected $_classAllowed = array();
/**
* Loader for classes in added directories
* @var Zend_Loader_PluginLoader
*/
protected $_loader;
/**
* @var bool Production flag; whether or not to return exception messages
*/
protected $_production = true;
/**
* Request processed
* @var null|Zend_Amf_Request
*/
protected $_request = null;
/**
* Class to use for responses
* @var null|Zend_Amf_Response
*/
protected $_response;
/**
* Dispatch table of name => method pairs
* @var array
*/
protected $_table = array();
/**
*
* @var bool session flag; whether or not to add a session to each response.
*/
protected $_session = false;
/**
* Namespace allows all AMF calls to not clobber other PHP session variables
* @var Zend_Session_NameSpace default session namespace zend_amf
*/
protected $_sesionNamespace = 'zend_amf';
/**
* Set the default session.name if php_
* @var string
*/
protected $_sessionName = 'PHPSESSID';
/**
* Authentication handler object
*
* @var Zend_Amf_Auth_Abstract
*/
protected $_auth;
/**
* ACL handler object
*
* @var Zend_Acl
*/
protected $_acl;
/**
* The server constructor
*/
public function __construct()
{
Zend_Amf_Parse_TypeLoader::setResourceLoader(new Zend_Loader_PluginLoader(array("Zend_Amf_Parse_Resource" => "Zend/Amf/Parse/Resource")));
}
/**
* Set authentication adapter
*
* If the authentication adapter implements a "getAcl()" method, populate
* the ACL of this instance with it (if none exists already).
*
* @param Zend_Amf_Auth_Abstract $auth
* @return Zend_Amf_Server
*/
public function setAuth(Zend_Amf_Auth_Abstract $auth)
{
$this->_auth = $auth;
if ((null === $this->getAcl()) && method_exists($auth, 'getAcl')) {
$this->setAcl($auth->getAcl());
}
return $this;
}
/**
* Get authentication adapter
*
* @return Zend_Amf_Auth_Abstract
*/
public function getAuth()
{
return $this->_auth;
}
/**
* Set ACL adapter
*
* @param Zend_Acl $acl
* @return Zend_Amf_Server
*/
public function setAcl(Zend_Acl $acl)
{
$this->_acl = $acl;
return $this;
}
/**
* Get ACL adapter
*
* @return Zend_Acl
*/
public function getAcl()
{
return $this->_acl;
}
/**
* Set production flag
*
* @param bool $flag
* @return Zend_Amf_Server
*/
public function setProduction($flag)
{
$this->_production = (bool) $flag;
return $this;
}
/**
* Whether or not the server is in production
*
* @return bool
*/
public function isProduction()
{
return $this->_production;
}
/**
* @param namespace of all incoming sessions defaults to Zend_Amf
* @return Zend_Amf_Server
*/
public function setSession($namespace = 'Zend_Amf')
{
require_once 'Zend/Session.php';
$this->_session = true;
$this->_sesionNamespace = new Zend_Session_Namespace($namespace);
return $this;
}
/**
* Whether of not the server is using sessions
* @return bool
*/
public function isSession()
{
return $this->_session;
}
/**
* Check if the ACL allows accessing the function or method
*
* @param string|object $object Object or class being accessed
* @param string $function Function or method being accessed
* @return unknown_type
*/
protected function _checkAcl($object, $function)
{
if(!$this->_acl) {
return true;
}
if($object) {
$class = is_object($object)?get_class($object):$object;
if(!$this->_acl->has($class)) {
require_once 'Zend/Acl/Resource.php';
$this->_acl->add(new Zend_Acl_Resource($class));
}
$call = array($object, "initAcl");
if(is_callable($call) && !call_user_func($call, $this->_acl)) {
// if initAcl returns false, no ACL check
return true;
}
} else {
$class = null;
}
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$role = $auth->getIdentity()->role;
} else {
if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) {
$role = Zend_Amf_Constants::GUEST_ROLE;
} else {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed");
}
}
if($this->_acl->isAllowed($role, $class, $function)) {
return true;
} else {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception("Access not allowed");
}
}
/**
* Get PluginLoader for the Server
*
* @return Zend_Loader_PluginLoader
*/
protected function getLoader()
{
if(empty($this->_loader)) {
require_once 'Zend/Loader/PluginLoader.php';
$this->_loader = new Zend_Loader_PluginLoader();
}
return $this->_loader;
}
/**
* Loads a remote class or method and executes the function and returns
* the result
*
* @param string $method Is the method to execute
* @param mixed $param values for the method
* @return mixed $response the result of executing the method
* @throws Zend_Amf_Server_Exception
*/
protected function _dispatch($method, $params = null, $source = null)
{
if($source) {
if(($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) {
$source = $mapped;
}
}
$qualifiedName = empty($source) ? $method : $source . '.' . $method;
if (!isset($this->_table[$qualifiedName])) {
// if source is null a method that was not defined was called.
if ($source) {
$className = str_replace('.', '_', $source);
if(class_exists($className, false) && !isset($this->_classAllowed[$className])) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Can not call "' . $className . '" - use setClass()');
}
try {
$this->getLoader()->load($className);
} catch (Exception $e) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist: '.$e->getMessage(), 0, $e);
}
// Add the new loaded class to the server.
$this->setClass($className, $source);
}
if (!isset($this->_table[$qualifiedName])) {
// Source is null or doesn't contain specified method
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist');
}
}
$info = $this->_table[$qualifiedName];
$argv = $info->getInvokeArguments();
if (0 < count($argv)) {
$params = array_merge($params, $argv);
}
if ($info instanceof Zend_Server_Reflection_Function) {
$func = $info->getName();
$this->_checkAcl(null, $func);
$return = call_user_func_array($func, $params);
} elseif ($info instanceof Zend_Server_Reflection_Method) {
// Get class
$class = $info->getDeclaringClass()->getName();
if ('static' == $info->isStatic()) {
// for some reason, invokeArgs() does not work the same as
// invoke(), and expects the first argument to be an object.
// So, using a callback if the method is static.
$this->_checkAcl($class, $info->getName());
$return = call_user_func_array(array($class, $info->getName()), $params);
} else {
// Object methods
try {
$object = $info->getDeclaringClass()->newInstance();
} catch (Exception $e) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $info->getName() . ': '.$e->getMessage(), 621, $e);
}
$this->_checkAcl($object, $info->getName());
$return = $info->invokeArgs($object, $params);
}
} else {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Method missing implementation ' . get_class($info));
}
return $return;
}
/**
* Handles each of the 11 different command message types.
*
* A command message is a flex.messaging.messages.CommandMessage
*
* @see Zend_Amf_Value_Messaging_CommandMessage
* @param Zend_Amf_Value_Messaging_CommandMessage $message
* @return Zend_Amf_Value_Messaging_AcknowledgeMessage
*/
protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
{
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
switch($message->operation) {
case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION :
case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION :
$data = explode(':', base64_decode($message->body));
$userid = $data[0];
$password = isset($data[1])?$data[1]:"";
if(empty($userid)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Login failed: username not supplied');
}
if(!$this->_handleAuth($userid, $password)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Authentication failed');
}
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION :
if($this->_auth) {
Zend_Auth::getInstance()->clearIdentity();
}
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
break;
default :
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
break;
}
return $return;
}
/**
* Create appropriate error message
*
* @param int $objectEncoding Current AMF encoding
* @param string $message Message that was being processed when error happened
* @param string $description Error description
* @param mixed $detail Detailed data about the error
* @param int $code Error code
* @param int $line Error line
* @return Zend_Amf_Value_Messaging_ErrorMessage|array
*/
protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line)
{
$return = null;
switch ($objectEncoding) {
case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
return array (
'description' => ($this->isProduction ()) ? '' : $description,
'detail' => ($this->isProduction ()) ? '' : $detail,
'line' => ($this->isProduction ()) ? 0 : $line,
'code' => $code
);
case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
$return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message );
$return->faultString = $this->isProduction () ? '' : $description;
$return->faultCode = $code;
$return->faultDetail = $this->isProduction () ? '' : $detail;
break;
}
return $return;
}
/**
* Handle AMF authentication
*
* @param string $userid
* @param string $password
* @return boolean
*/
protected function _handleAuth( $userid, $password)
{
if (!$this->_auth) {
return true;
}
$this->_auth->setCredentials($userid, $password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($this->_auth);
if ($result->isValid()) {
if (!$this->isSession()) {
$this->setSession();
}
return true;
} else {
// authentication failed, good bye
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception(
"Authentication failed: " . join("\n",
$result->getMessages()), $result->getCode());
}
}
/**
* Takes the deserialized AMF request and performs any operations.
*
* @todo should implement and SPL observer pattern for custom AMF headers
* @todo DescribeService support
* @param Zend_Amf_Request $request
* @return Zend_Amf_Response
* @throws Zend_Amf_server_Exception|Exception
*/
protected function _handle(Zend_Amf_Request $request)
{
// Get the object encoding of the request.
$objectEncoding = $request->getObjectEncoding();
// create a response object to place the output from the services.
$response = $this->getResponse();
// set response encoding
$response->setObjectEncoding($objectEncoding);
// Authenticate, if we have credential headers
$error = false;
$headers = $request->getAmfHeaders();
if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER])
&& isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid)
&& isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password)
) {
try {
if ($this->_handleAuth(
$headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid,
$headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password
)) {
// use RequestPersistentHeader to clear credentials
$response->addAmfHeader(
new Zend_Amf_Value_MessageHeader(
Zend_Amf_Constants::PERSISTENT_HEADER,
false,
new Zend_Amf_Value_MessageHeader(
Zend_Amf_Constants::CREDENTIALS_HEADER,
false, null
)
)
);
}
} catch (Exception $e) {
// Error during authentication; report it
$error = $this->_errorMessage(
$objectEncoding,
'',
$e->getMessage(),
$e->getTraceAsString(),
$e->getCode(),
$e->getLine()
);
$responseType = Zend_AMF_Constants::STATUS_METHOD;
}
}
// Iterate through each of the service calls in the AMF request
foreach($request->getAmfBodies() as $body)
{
if ($error) {
// Error during authentication; just report it and be done
$responseURI = $body->getResponseURI() . $responseType;
$newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $error);
$response->addAmfBody($newBody);
continue;
}
try {
switch ($objectEncoding) {
case Zend_Amf_Constants::AMF0_OBJECT_ENCODING:
// AMF0 Object Encoding
$targetURI = $body->getTargetURI();
$message = '';
// Split the target string into its values.
$source = substr($targetURI, 0, strrpos($targetURI, '.'));
if ($source) {
// Break off method name from namespace into source
$method = substr(strrchr($targetURI, '.'), 1);
$return = $this->_dispatch($method, $body->getData(), $source);
} else {
// Just have a method name.
$return = $this->_dispatch($targetURI, $body->getData());
}
break;
case Zend_Amf_Constants::AMF3_OBJECT_ENCODING:
default:
// AMF3 read message type
$message = $body->getData();
if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) {
// async call with command message
$return = $this->_loadCommandMessage($message);
} elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) {
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
$return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
$return->body = $this->_dispatch($message->operation, $message->body, $message->source);
} else {
// Amf3 message sent with netConnection
$targetURI = $body->getTargetURI();
// Split the target string into its values.
$source = substr($targetURI, 0, strrpos($targetURI, '.'));
if ($source) {
// Break off method name from namespace into source
$method = substr(strrchr($targetURI, '.'), 1);
$return = $this->_dispatch($method, $body->getData(), $source);
} else {
// Just have a method name.
$return = $this->_dispatch($targetURI, $body->getData());
}
}
break;
}
$responseType = Zend_AMF_Constants::RESULT_METHOD;
} catch (Exception $e) {
$return = $this->_errorMessage($objectEncoding, $message,
$e->getMessage(), $e->getTraceAsString(),$e->getCode(), $e->getLine());
$responseType = Zend_AMF_Constants::STATUS_METHOD;
}
$responseURI = $body->getResponseURI() . $responseType;
$newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
$response->addAmfBody($newBody);
}
// Add a session header to the body if session is requested.
if($this->isSession()) {
$currentID = session_id();
$joint = "?";
if(isset($_SERVER['QUERY_STRING'])) {
if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
$joint = "&";
}
}
}
// create a new AMF message header with the session id as a variable.
$sessionValue = $joint . $this->_sessionName . "=" . $currentID;
$sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue);
$response->addAmfHeader($sessionHeader);
}
// serialize the response and return serialized body.
$response->finalize();
}
/**
* Handle an AMF call from the gateway.
*
* @param null|Zend_Amf_Request $request Optional
* @return Zend_Amf_Response
*/
public function handle($request = null)
{
// Check if request was passed otherwise get it from the server
if ($request === null || !$request instanceof Zend_Amf_Request) {
$request = $this->getRequest();
} else {
$this->setRequest($request);
}
if ($this->isSession()) {
// Check if a session is being sent from the amf call
if (isset($_COOKIE[$this->_sessionName])) {
session_id($_COOKIE[$this->_sessionName]);
}
}
// Check for errors that may have happend in deserialization of Request.
try {
// Take converted PHP objects and handle service call.
// Serialize to Zend_Amf_response for output stream
$this->_handle($request);
$response = $this->getResponse();
} catch (Exception $e) {
// Handle any errors in the serialization and service calls.
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine(), 0, $e);
}
// Return the Amf serialized output string
return $response;
}
/**
* Set request object
*
* @param string|Zend_Amf_Request $request
* @return Zend_Amf_Server
*/
public function setRequest($request)
{
if (is_string($request) && class_exists($request)) {
$request = new $request();
if (!$request instanceof Zend_Amf_Request) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid request class');
}
} elseif (!$request instanceof Zend_Amf_Request) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid request object');
}
$this->_request = $request;
return $this;
}
/**
* Return currently registered request object
*
* @return null|Zend_Amf_Request
*/
public function getRequest()
{
if (null === $this->_request) {
require_once 'Zend/Amf/Request/Http.php';
$this->setRequest(new Zend_Amf_Request_Http());
}
return $this->_request;
}
/**
* Public access method to private Zend_Amf_Server_Response reference
*
* @param string|Zend_Amf_Server_Response $response
* @return Zend_Amf_Server
*/
public function setResponse($response)
{
if (is_string($response) && class_exists($response)) {
$response = new $response();
if (!$response instanceof Zend_Amf_Response) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid response class');
}
} elseif (!$response instanceof Zend_Amf_Response) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid response object');
}
$this->_response = $response;
return $this;
}
/**
* get a reference to the Zend_Amf_response instance
*
* @return Zend_Amf_Server_Response
*/
public function getResponse()
{
if (null === ($response = $this->_response)) {
require_once 'Zend/Amf/Response/Http.php';
$this->setResponse(new Zend_Amf_Response_Http());
}
return $this->_response;
}
/**
* Attach a class or object to the server
*
* Class may be either a class name or an instantiated object. Reflection
* is done on the class or object to determine the available public
* methods, and each is attached to the server as and available method. If
* a $namespace has been provided, that namespace is used to prefix
* AMF service call.
*
* @param string|object $class
* @param string $namespace Optional
* @param mixed $arg Optional arguments to pass to a method
* @return Zend_Amf_Server
* @throws Zend_Amf_Server_Exception on invalid input
*/
public function setClass($class, $namespace = '', $argv = null)
{
if (is_string($class) && !class_exists($class)){
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid method or class');
} elseif (!is_string($class) && !is_object($class)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object');
}
$argv = null;
if (2 < func_num_args()) {
$argv = array_slice(func_get_args(), 2);
}
// Use the class name as the name space by default.
if ($namespace == '') {
$namespace = is_object($class) ? get_class($class) : $class;
}
$this->_classAllowed[is_object($class) ? get_class($class) : $class] = true;
$this->_methods[] = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
$this->_buildDispatchTable();
return $this;
}
/**
* Attach a function to the server
*
* Additional arguments to pass to the function at dispatch may be passed;
* any arguments following the namespace will be aggregated and passed at
* dispatch time.
*
* @param string|array $function Valid callback
* @param string $namespace Optional namespace prefix
* @return Zend_Amf_Server
* @throws Zend_Amf_Server_Exception
*/
public function addFunction($function, $namespace = '')
{
if (!is_string($function) && !is_array($function)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Unable to attach function');
}
$argv = null;
if (2 < func_num_args()) {
$argv = array_slice(func_get_args(), 2);
}
$function = (array) $function;
foreach ($function as $func) {
if (!is_string($func) || !function_exists($func)) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Unable to attach function');
}
$this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace);
}
$this->_buildDispatchTable();
return $this;
}
/**
* Creates an array of directories in which services can reside.
* TODO: add support for prefixes?
*
* @param string $dir
*/
public function addDirectory($dir)
{
$this->getLoader()->addPrefixPath("", $dir);
}
/**
* Returns an array of directories that can hold services.
*
* @return array
*/
public function getDirectory()
{
return $this->getLoader()->getPaths("");
}
/**
* (Re)Build the dispatch table
*
* The dispatch table consists of a an array of method name =>
* Zend_Server_Reflection_Function_Abstract pairs
*
* @return void
*/
protected function _buildDispatchTable()
{
$table = array();
foreach ($this->_methods as $key => $dispatchable) {
if ($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) {
$ns = $dispatchable->getNamespace();
$name = $dispatchable->getName();
$name = empty($ns) ? $name : $ns . '.' . $name;
if (isset($table[$name])) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
}
$table[$name] = $dispatchable;
continue;
}
if ($dispatchable instanceof Zend_Server_Reflection_Class) {
foreach ($dispatchable->getMethods() as $method) {
$ns = $method->getNamespace();
$name = $method->getName();
$name = empty($ns) ? $name : $ns . '.' . $name;
if (isset($table[$name])) {
require_once 'Zend/Amf/Server/Exception.php';
throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
}
$table[$name] = $method;
continue;
}
}
}
$this->_table = $table;
}
/**
* Raise a server fault
*
* Unimplemented
*
* @param string|Exception $fault
* @return void
*/
public function fault($fault = null, $code = 404)
{
}
/**
* Returns a list of registered methods
*
* Returns an array of dispatchables (Zend_Server_Reflection_Function,
* _Method, and _Class items).
*
* @return array
*/
public function getFunctions()
{
return $this->_table;
}
/**
* Set server persistence
*
* Unimplemented
*
* @param mixed $mode
* @return void
*/
public function setPersistence($mode)
{
}
/**
* Load server definition
*
* Unimplemented
*
* @param array $definition
* @return void
*/
public function loadFunctions($definition)
{
}
/**
* Map ActionScript classes to PHP classes
*
* @param string $asClass
* @param string $phpClass
* @return Zend_Amf_Server
*/
public function setClassMap($asClass, $phpClass)
{
require_once 'Zend/Amf/Parse/TypeLoader.php';
Zend_Amf_Parse_TypeLoader::setMapping($asClass, $phpClass);
return $this;
}
/**
* List all available methods
*
* Returns an array of method names.
*
* @return array
*/
public function listMethods()
{
return array_keys($this->_table);
}
}

View File

@ -1,37 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Server
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Exception */
require_once 'Zend/Amf/Exception.php';
/**
* Zend_Amf_Server_Exception
*
* @category Zend
* @package Zend_Amf
* @subpackage Server
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Server_Exception extends Zend_Amf_Exception
{
}

View File

@ -1,285 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BinaryStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Utility class to walk through a data stream byte by byte with conventional names
*
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Util_BinaryStream
{
/**
* @var string Byte stream
*/
protected $_stream;
/**
* @var int Length of stream
*/
protected $_streamLength;
/**
* @var bool BigEndian encoding?
*/
protected $_bigEndian;
/**
* @var int Current position in stream
*/
protected $_needle;
/**
* Constructor
*
* Create a reference to a byte stream that is going to be parsed or created
* by the methods in the class. Detect if the class should use big or
* little Endian encoding.
*
* @param string $stream use '' if creating a new stream or pass a string if reading.
* @return void
*/
public function __construct($stream)
{
if (!is_string($stream)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Inputdata is not of type String');
}
$this->_stream = $stream;
$this->_needle = 0;
$this->_streamLength = strlen($stream);
$this->_bigEndian = (pack('l', 1) === "\x00\x00\x00\x01");
}
/**
* Returns the current stream
*
* @return string
*/
public function getStream()
{
return $this->_stream;
}
/**
* Read the number of bytes in a row for the length supplied.
*
* @todo Should check that there are enough bytes left in the stream we are about to read.
* @param int $length
* @return string
* @throws Zend_Amf_Exception for buffer underrun
*/
public function readBytes($length)
{
if (($length + $this->_needle) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
$bytes = substr($this->_stream, $this->_needle, $length);
$this->_needle+= $length;
return $bytes;
}
/**
* Write any length of bytes to the stream
*
* Usually a string.
*
* @param string $bytes
* @return Zend_Amf_Util_BinaryStream
*/
public function writeBytes($bytes)
{
$this->_stream.= $bytes;
return $this;
}
/**
* Reads a signed byte
*
* @return int Value is in the range of -128 to 127.
*/
public function readByte()
{
if (($this->_needle + 1) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
return ord($this->_stream{$this->_needle++});
}
/**
* Writes the passed string into a signed byte on the stream.
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeByte($stream)
{
$this->_stream.= pack('c', $stream);
return $this;
}
/**
* Reads a signed 32-bit integer from the data stream.
*
* @return int Value is in the range of -2147483648 to 2147483647
*/
public function readInt()
{
return ($this->readByte() << 8) + $this->readByte();
}
/**
* Write an the integer to the output stream as a 32 bit signed integer
*
* @param int $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeInt($stream)
{
$this->_stream.= pack('n', $stream);
return $this;
}
/**
* Reads a UTF-8 string from the data stream
*
* @return string A UTF-8 string produced by the byte representation of characters
*/
public function readUtf()
{
$length = $this->readInt();
return $this->readBytes($length);
}
/**
* Wite a UTF-8 string to the outputstream
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeUtf($stream)
{
$this->writeInt(strlen($stream));
$this->_stream.= $stream;
return $this;
}
/**
* Read a long UTF string
*
* @return string
*/
public function readLongUtf()
{
$length = $this->readLong();
return $this->readBytes($length);
}
/**
* Write a long UTF string to the buffer
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLongUtf($stream)
{
$this->writeLong(strlen($stream));
$this->_stream.= $stream;
}
/**
* Read a long numeric value
*
* @return double
*/
public function readLong()
{
return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
}
/**
* Write long numeric value to output stream
*
* @param int|string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLong($stream)
{
$this->_stream.= pack('N', $stream);
return $this;
}
/**
* Read a 16 bit unsigned short.
*
* @todo This could use the unpack() w/ S,n, or v
* @return double
*/
public function readUnsignedShort()
{
$byte1 = $this->readByte();
$byte2 = $this->readByte();
return (($byte1 << 8) | $byte2);
}
/**
* Reads an IEEE 754 double-precision floating point number from the data stream.
*
* @return double Floating point number
*/
public function readDouble()
{
$bytes = substr($this->_stream, $this->_needle, 8);
$this->_needle+= 8;
if (!$this->_bigEndian) {
$bytes = strrev($bytes);
}
$double = unpack('dflt', $bytes);
return $double['flt'];
}
/**
* Writes an IEEE 754 double-precision floating point number from the data stream.
*
* @param string|double $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeDouble($stream)
{
$stream = pack('d', $stream);
if (!$this->_bigEndian) {
$stream = strrev($stream);
}
$this->_stream.= $stream;
return $this;
}
}

View File

@ -1,58 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ByteArray.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Wrapper class to store an AMF3 flash.utils.ByteArray
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_ByteArray
{
/**
* @var string ByteString Data
*/
protected $_data = '';
/**
* Create a ByteArray
*
* @param string $data
* @return void
*/
public function __construct($data)
{
$this->_data = $data;
}
/**
* Return the byte stream
*
* @return string
*/
public function getData()
{
return $this->_data;
}
}

View File

@ -1,182 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MessageBody.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* An AMF Message contains information about the actual individual
* transaction that is to be performed. It specifies the remote
* operation that is to be performed; a local (client) operation
* to be invoked upon success; and, the data to be used in the
* operation.
* <p/>
* This Message structure defines how a local client would
* invoke a method/operation on a remote server. Additionally,
* the response from the Server is structured identically.
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_MessageBody
{
/**
* A string describing which operation, function, or method
* is to be remotley invoked.
* @var string
*/
protected $_targetUri = "";
/**
* Universal Resource Identifier that uniquely targets the originator's
* Object that should receive the server's response. The server will
* use this path specification to target the "OnResult()" or "onStatus()"
* handlers within the client. For Flash, it specifies an ActionScript
* Object path only. The NetResponse object pointed to by the Response Uri
* contains the connection state information. Passing/specifying this
* provides a convenient mechanism for the client/server to share access
* to an object that is managing the state of the shared connection.
*
* Since the server will use this field in the event of an error,
* this field is required even if a successful server request would
* not be expected to return a value to the client.
*
* @var string
*/
protected $_responseUri = "";
/**
* Contains the actual data associated with the operation. It contains
* the client's parameter data that is passed to the server's operation/method.
* When serializing a root level data type or a parameter list array, no
* name field is included. That is, the data is anonomously represented
* as "Type Marker"/"Value" pairs. When serializing member data, the data is
* represented as a series of "Name"/"Type"/"Value" combinations.
*
* For server generated responses, it may contain any ActionScript
* data/objects that the server was expected to provide.
*
* @var string
*/
protected $_data;
/**
* Constructor
*
* @param string $targetUri
* @param string $responseUri
* @param string $data
* @return void
*/
public function __construct($targetUri, $responseUri, $data)
{
$this->setTargetUri($targetUri);
$this->setResponseUri($responseUri);
$this->setData($data);
}
/**
* Retrieve target Uri
*
* @return string
*/
public function getTargetUri()
{
return $this->_targetUri;
}
/**
* Set target Uri
*
* @param string $targetUri
* @return Zend_Amf_Value_MessageBody
*/
public function setTargetUri($targetUri)
{
if (null === $targetUri) {
$targetUri = '';
}
$this->_targetUri = (string) $targetUri;
return $this;
}
/**
* Get target Uri
*
* @return string
*/
public function getResponseUri()
{
return $this->_responseUri;
}
/**
* Set response Uri
*
* @param string $responseUri
* @return Zend_Amf_Value_MessageBody
*/
public function setResponseUri($responseUri)
{
if (null === $responseUri) {
$responseUri = '';
}
$this->_responseUri = $responseUri;
return $this;
}
/**
* Retrieve response data
*
* @return string
*/
public function getData()
{
return $this->_data;
}
/**
* Set response data
*
* @param mixed $data
* @return Zend_Amf_Value_MessageBody
*/
public function setData($data)
{
$this->_data = $data;
return $this;
}
/**
* Set reply method
*
* @param string $methodName
* @return Zend_Amf_Value_MessageBody
*/
public function setReplyMethod($methodName)
{
if (!preg_match('#^[/?]#', $methodName)) {
$this->_targetUri = rtrim($this->_targetUri, '/') . '/';
}
$this->_targetUri = $this->_targetUri . $methodName;
return $this;
}
}

View File

@ -1,81 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: MessageHeader.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Message Headers provide context for the processing of the
* the AMF Packet and all subsequent Messages.
*
* Multiple Message Headers may be included within an AMF Packet.
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_MessageHeader
{
/**
* Name of the header
*
* @var string
*/
public $name;
/**
* Flag if the data has to be parsed on return
*
* @var boolean
*/
public $mustRead;
/**
* Length of the data field
*
* @var int
*/
public $length;
/**
* Data sent with the header name
*
* @var mixed
*/
public $data;
/**
* Used to create and store AMF Header data.
*
* @param String $name
* @param Boolean $mustRead
* @param misc $content
* @param integer $length
*/
public function __construct($name, $mustRead, $data, $length=null)
{
$this->name = $name;
$this->mustRead = (bool) $mustRead;
$this->data = $data;
if (null !== $length) {
$this->length = (int) $length;
}
}
}

View File

@ -1,92 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AbstractMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This is the default Implementation of Message, which provides
* a convenient base for behavior and association of common endpoints
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_AbstractMessage
{
/**
* @var string Client identifier
*/
public $clientId;
/**
* @var string Destination
*/
public $destination;
/**
* @var string Message identifier
*/
public $messageId;
/**
* @var int Message timestamp
*/
public $timestamp;
/**
* @var int Message TTL
*/
public $timeToLive;
/**
* @var object Message headers
*/
public $headers;
/**
* @var string Message body
*/
public $body;
/**
* generate a unique id
*
* Format is: ########-####-####-####-############
* Where # is an uppercase letter or number
* example: 6D9DC7EC-A273-83A9-ABE3-00005FD752D6
*
* @return string
*/
public function generateId()
{
return sprintf(
'%08X-%04X-%04X-%02X%02X-%012X',
mt_rand(),
mt_rand(0, 65535),
bindec(substr_replace(
sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
),
bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
mt_rand(0, 255),
mt_rand()
);
}
}

View File

@ -1,60 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AcknowledgeMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Value_Messaging_AsyncMessage */
require_once 'Zend/Amf/Value/Messaging/AsyncMessage.php';
/**
* This is the type of message returned by the MessageBroker
* to endpoints after the broker has routed an endpoint's message
* to a service.
*
* flex.messaging.messages.AcknowledgeMessage
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_AcknowledgeMessage extends Zend_Amf_Value_Messaging_AsyncMessage
{
/**
* Create a new Acknowledge Message
*
* @param unknown_type $message
*/
public function __construct($message)
{
$this->clientId = $this->generateId();
$this->destination = null;
$this->messageId = $this->generateId();
$this->timestamp = time().'00';
$this->timeToLive = 0;
$this->headers = new STDClass();
$this->body = null;
// correleate the two messages
if ($message && isset($message->messageId)) {
$this->correlationId = $message->messageId;
}
}
}

View File

@ -1,35 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ArrayCollection.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Type encapsulating Flex ArrayCollection
*
* Corresponds to flex.messaging.io.ArrayCollection
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_ArrayCollection
{
}

View File

@ -1,43 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AsyncMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Value_Messaging_AbstractMessage */
require_once 'Zend/Amf/Value/Messaging/AbstractMessage.php';
/**
* This type of message contains information necessary to perform
* point-to-point or publish-subscribe messaging.
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_AsyncMessage extends Zend_Amf_Value_Messaging_AbstractMessage
{
/**
* The message id to be responded to.
* @var String
*/
public $correlationId;
}

View File

@ -1,119 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: CommandMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Amf_Value_Messaging_AsyncMessage
*/
require_once 'Zend/Amf/Value/Messaging/AsyncMessage.php';
/**
* A message that represents an infrastructure command passed between
* client and server. Subscribe/unsubscribe operations result in
* CommandMessage transmissions, as do polling operations.
*
* Corresponds to flex.messaging.messages.CommandMessage
*
* Note: THESE VALUES MUST BE THE SAME ON CLIENT AND SERVER
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_CommandMessage extends Zend_Amf_Value_Messaging_AsyncMessage
{
/**
* This operation is used to subscribe to a remote destination.
*/
const SUBSCRIBE_OPERATION = 0;
/**
* This operation is used to unsubscribe from a remote destination.
*/
const UNSUSBSCRIBE_OPERATION = 1;
/**
* This operation is used to poll a remote destination for pending,
* undelivered messages.
*/
const POLL_OPERATION = 2;
/**
* This operation is used by a remote destination to sync missed or cached messages
* back to a client as a result of a client issued poll command.
*/
const CLIENT_SYNC_OPERATION = 4;
/**
* This operation is used to test connectivity over the current channel to
* the remote endpoint.
*/
const CLIENT_PING_OPERATION = 5;
/**
* This operation is used to request a list of failover endpoint URIs
* for the remote destination based on cluster membership.
*/
const CLUSTER_REQUEST_OPERATION = 7;
/**
* This operation is used to send credentials to the endpoint so that
* the user can be logged in over the current channel.
* The credentials need to be Base64 encoded and stored in the <code>body</code>
* of the message.
*/
const LOGIN_OPERATION = 8;
/**
* This operation is used to log the user out of the current channel, and
* will invalidate the server session if the channel is HTTP based.
*/
const LOGOUT_OPERATION = 9;
/**
* This operation is used to indicate that the client's subscription to a
* remote destination has been invalidated.
*/
const SESSION_INVALIDATE_OPERATION = 10;
/**
* This operation is used by the MultiTopicConsumer to subscribe/unsubscribe
* from multiple subtopics/selectors in the same message.
*/
const MULTI_SUBSCRIBE_OPERATION = 11;
/**
* This operation is used to indicate that a channel has disconnected
*/
const DISCONNECT_OPERATION = 12;
/**
* This is the default operation for new CommandMessage instances.
*/
const UNKNOWN_OPERATION = 10000;
/**
* The operation to execute for messages of this type
* @var int
*/
public $operation = self::UNKNOWN_OPERATION;
}

View File

@ -1,67 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ErrorMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Amf_Value_Messaging_AcknowledgeMessage */
require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
/**
* Creates the error message to report to flex the issue with the call
*
* Corresponds to flex.messaging.messages.ErrorMessage
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_ErrorMessage extends Zend_Amf_Value_Messaging_AcknowledgeMessage
{
/**
* Additional data with error
* @var object
*/
public $extendedData = null;
/**
* Error code number
* @var string
*/
public $faultCode;
/**
* Description as to the cause of the error
* @var string
*/
public $faultDetail;
/**
* Short description of error
* @var string
*/
public $faultString = '';
/**
* root cause of error
* @var object
*/
public $rootCause = null;
}

View File

@ -1,73 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: RemotingMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Amf_Value_Messaging_AbstractMessage */
require_once 'Zend/Amf/Value/Messaging/AbstractMessage.php';
/**
* This type of message contains information needed to perform
* a Remoting invocation.
*
* Corresponds to flex.messaging.messages.RemotingMessage
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_RemotingMessage extends Zend_Amf_Value_Messaging_AbstractMessage
{
/**
* The name of the service to be called including package name
* @var String
*/
public $source;
/**
* The name of the method to be called
* @var string
*/
public $operation;
/**
* The arguments to call the mathod with
* @var array
*/
public $parameters;
/**
* Create a new Remoting Message
*
* @return void
*/
public function __construct()
{
$this->clientId = $this->generateId();
$this->destination = null;
$this->messageId = $this->generateId();
$this->timestamp = time().'00';
$this->timeToLive = 0;
$this->headers = new stdClass();
$this->body = null;
}
}

View File

@ -1,154 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TraitsInfo.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Amf_Value_TraitsInfo
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_TraitsInfo
{
/**
* @var string Class name
*/
protected $_className;
/**
* @var bool Whether or not this is a dynamic class
*/
protected $_dynamic;
/**
* @var bool Whether or not the class is externalizable
*/
protected $_externalizable;
/**
* @var array Class properties
*/
protected $_properties;
/**
* Used to keep track of all class traits of an AMF3 object
*
* @param string $className
* @param boolean $dynamic
* @param boolean $externalizable
* @param boolean $properties
* @return void
*/
public function __construct($className, $dynamic=false, $externalizable=false, $properties=null)
{
$this->_className = $className;
$this->_dynamic = $dynamic;
$this->_externalizable = $externalizable;
$this->_properties = $properties;
}
/**
* Test if the class is a dynamic class
*
* @return boolean
*/
public function isDynamic()
{
return $this->_dynamic;
}
/**
* Test if class is externalizable
*
* @return boolean
*/
public function isExternalizable()
{
return $this->_externalizable;
}
/**
* Return the number of properties in the class
*
* @return int
*/
public function length()
{
return count($this->_properties);
}
/**
* Return the class name
*
* @return string
*/
public function getClassName()
{
return $this->_className;
}
/**
* Add an additional property
*
* @param string $name
* @return Zend_Amf_Value_TraitsInfo
*/
public function addProperty($name)
{
$this->_properties[] = $name;
return $this;
}
/**
* Add all properties of the class.
*
* @param array $props
* @return Zend_Amf_Value_TraitsInfo
*/
public function addAllProperties(array $props)
{
$this->_properties = $props;
return $this;
}
/**
* Get the property at a given index
*
* @param int $index
* @return string
*/
public function getProperty($index)
{
return $this->_properties[(int) $index];
}
/**
* Return all properties of the class.
*
* @return array
*/
public function getAllProperties()
{
return $this->_properties;
}
}

View File

@ -1,417 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Application
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Application.php 24101 2011-06-01 02:21:15Z adamlundrigan $
*/
/**
* @category Zend
* @package Zend_Application
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Application
{
/**
* Autoloader to use
*
* @var Zend_Loader_Autoloader
*/
protected $_autoloader;
/**
* Bootstrap
*
* @var Zend_Application_Bootstrap_BootstrapAbstract
*/
protected $_bootstrap;
/**
* Application environment
*
* @var string
*/
protected $_environment;
/**
* Flattened (lowercase) option keys
*
* @var array
*/
protected $_optionKeys = array();
/**
* Options for Zend_Application
*
* @var array
*/
protected $_options = array();
/**
* Constructor
*
* Initialize application. Potentially initializes include_paths, PHP
* settings, and bootstrap class.
*
* @param string $environment
* @param string|array|Zend_Config $options String path to configuration file, or array/Zend_Config of configuration options
* @throws Zend_Application_Exception When invalid options are provided
* @return void
*/
public function __construct($environment, $options = null)
{
$this->_environment = (string) $environment;
require_once 'Zend/Loader/Autoloader.php';
$this->_autoloader = Zend_Loader_Autoloader::getInstance();
if (null !== $options) {
if (is_string($options)) {
$options = $this->_loadConfig($options);
} elseif ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
throw new Zend_Application_Exception('Invalid options provided; must be location of config file, a config object, or an array');
}
$this->setOptions($options);
}
}
/**
* Retrieve current environment
*
* @return string
*/
public function getEnvironment()
{
return $this->_environment;
}
/**
* Retrieve autoloader instance
*
* @return Zend_Loader_Autoloader
*/
public function getAutoloader()
{
return $this->_autoloader;
}
/**
* Set application options
*
* @param array $options
* @throws Zend_Application_Exception When no bootstrap path is provided
* @throws Zend_Application_Exception When invalid bootstrap information are provided
* @return Zend_Application
*/
public function setOptions(array $options)
{
if (!empty($options['config'])) {
if (is_array($options['config'])) {
$_options = array();
foreach ($options['config'] as $tmp) {
$_options = $this->mergeOptions($_options, $this->_loadConfig($tmp));
}
$options = $this->mergeOptions($_options, $options);
} else {
$options = $this->mergeOptions($this->_loadConfig($options['config']), $options);
}
}
$this->_options = $options;
$options = array_change_key_case($options, CASE_LOWER);
$this->_optionKeys = array_keys($options);
if (!empty($options['phpsettings'])) {
$this->setPhpSettings($options['phpsettings']);
}
if (!empty($options['includepaths'])) {
$this->setIncludePaths($options['includepaths']);
}
if (!empty($options['autoloadernamespaces'])) {
$this->setAutoloaderNamespaces($options['autoloadernamespaces']);
}
if (!empty($options['autoloaderzfpath'])) {
$autoloader = $this->getAutoloader();
if (method_exists($autoloader, 'setZfPath')) {
$zfPath = $options['autoloaderzfpath'];
$zfVersion = !empty($options['autoloaderzfversion'])
? $options['autoloaderzfversion']
: 'latest';
$autoloader->setZfPath($zfPath, $zfVersion);
}
}
if (!empty($options['bootstrap'])) {
$bootstrap = $options['bootstrap'];
if (is_string($bootstrap)) {
$this->setBootstrap($bootstrap);
} elseif (is_array($bootstrap)) {
if (empty($bootstrap['path'])) {
throw new Zend_Application_Exception('No bootstrap path provided');
}
$path = $bootstrap['path'];
$class = null;
if (!empty($bootstrap['class'])) {
$class = $bootstrap['class'];
}
$this->setBootstrap($path, $class);
} else {
throw new Zend_Application_Exception('Invalid bootstrap information provided');
}
}
return $this;
}
/**
* Retrieve application options (for caching)
*
* @return array
*/
public function getOptions()
{
return $this->_options;
}
/**
* Is an option present?
*
* @param string $key
* @return bool
*/
public function hasOption($key)
{
return in_array(strtolower($key), $this->_optionKeys);
}
/**
* Retrieve a single option
*
* @param string $key
* @return mixed
*/
public function getOption($key)
{
if ($this->hasOption($key)) {
$options = $this->getOptions();
$options = array_change_key_case($options, CASE_LOWER);
return $options[strtolower($key)];
}
return null;
}
/**
* Merge options recursively
*
* @param array $array1
* @param mixed $array2
* @return array
*/
public function mergeOptions(array $array1, $array2 = null)
{
if (is_array($array2)) {
foreach ($array2 as $key => $val) {
if (is_array($array2[$key])) {
$array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key]))
? $this->mergeOptions($array1[$key], $array2[$key])
: $array2[$key];
} else {
$array1[$key] = $val;
}
}
}
return $array1;
}
/**
* Set PHP configuration settings
*
* @param array $settings
* @param string $prefix Key prefix to prepend to array values (used to map . separated INI values)
* @return Zend_Application
*/
public function setPhpSettings(array $settings, $prefix = '')
{
foreach ($settings as $key => $value) {
$key = empty($prefix) ? $key : $prefix . $key;
if (is_scalar($value)) {
ini_set($key, $value);
} elseif (is_array($value)) {
$this->setPhpSettings($value, $key . '.');
}
}
return $this;
}
/**
* Set include path
*
* @param array $paths
* @return Zend_Application
*/
public function setIncludePaths(array $paths)
{
$path = implode(PATH_SEPARATOR, $paths);
set_include_path($path . PATH_SEPARATOR . get_include_path());
return $this;
}
/**
* Set autoloader namespaces
*
* @param array $namespaces
* @return Zend_Application
*/
public function setAutoloaderNamespaces(array $namespaces)
{
$autoloader = $this->getAutoloader();
foreach ($namespaces as $namespace) {
$autoloader->registerNamespace($namespace);
}
return $this;
}
/**
* Set bootstrap path/class
*
* @param string $path
* @param string $class
* @return Zend_Application
*/
public function setBootstrap($path, $class = null)
{
// setOptions() can potentially send a null value; specify default
// here
if (null === $class) {
$class = 'Bootstrap';
}
if (!class_exists($class, false)) {
require_once $path;
if (!class_exists($class, false)) {
throw new Zend_Application_Exception('Bootstrap class not found');
}
}
$this->_bootstrap = new $class($this);
if (!$this->_bootstrap instanceof Zend_Application_Bootstrap_Bootstrapper) {
throw new Zend_Application_Exception('Bootstrap class does not implement Zend_Application_Bootstrap_Bootstrapper');
}
return $this;
}
/**
* Get bootstrap object
*
* @return Zend_Application_Bootstrap_BootstrapAbstract
*/
public function getBootstrap()
{
if (null === $this->_bootstrap) {
$this->_bootstrap = new Zend_Application_Bootstrap_Bootstrap($this);
}
return $this->_bootstrap;
}
/**
* Bootstrap application
*
* @param null|string|array $resource
* @return Zend_Application
*/
public function bootstrap($resource = null)
{
$this->getBootstrap()->bootstrap($resource);
return $this;
}
/**
* Run the application
*
* @return void
*/
public function run()
{
$this->getBootstrap()->run();
}
/**
* Load configuration file of options
*
* @param string $file
* @throws Zend_Application_Exception When invalid configuration file is provided
* @return array
*/
protected function _loadConfig($file)
{
$environment = $this->getEnvironment();
$suffix = pathinfo($file, PATHINFO_EXTENSION);
$suffix = ($suffix === 'dist')
? pathinfo(basename($file, ".$suffix"), PATHINFO_EXTENSION)
: $suffix;
switch (strtolower($suffix)) {
case 'ini':
$config = new Zend_Config_Ini($file, $environment);
break;
case 'xml':
$config = new Zend_Config_Xml($file, $environment);
break;
case 'json':
$config = new Zend_Config_Json($file, $environment);
break;
case 'yaml':
case 'yml':
$config = new Zend_Config_Yaml($file, $environment);
break;
case 'php':
case 'inc':
$config = include $file;
if (!is_array($config)) {
throw new Zend_Application_Exception('Invalid configuration file provided; PHP file does not return array value');
}
return $config;
break;
default:
throw new Zend_Application_Exception('Invalid configuration file provided; unknown config type');
}
return $config->toArray();
}
}

View File

@ -1,156 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Application
* @subpackage Bootstrap
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Bootstrap.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Concrete base class for bootstrap classes
*
* Registers and utilizes Zend_Controller_Front by default.
*
* @uses Zend_Application_Bootstrap_Bootstrap
* @category Zend
* @package Zend_Application
* @subpackage Bootstrap
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Application_Bootstrap_Bootstrap
extends Zend_Application_Bootstrap_BootstrapAbstract
{
/**
* Application resource namespace
* @var false|string
*/
protected $_appNamespace = false;
/**
* Application resource autoloader
* @var Zend_Loader_Autoloader_Resource
*/
protected $_resourceLoader;
/**
* Constructor
*
* Ensure FrontController resource is registered
*
* @param Zend_Application|Zend_Application_Bootstrap_Bootstrapper $application
* @return void
*/
public function __construct($application)
{
parent::__construct($application);
if ($application->hasOption('resourceloader')) {
$this->setOptions(array(
'resourceloader' => $application->getOption('resourceloader')
));
}
$this->getResourceLoader();
if (!$this->hasPluginResource('FrontController')) {
$this->registerPluginResource('FrontController');
}
}
/**
* Run the application
*
* Checks to see that we have a default controller directory. If not, an
* exception is thrown.
*
* If so, it registers the bootstrap with the 'bootstrap' parameter of
* the front controller, and dispatches the front controller.
*
* @return mixed
* @throws Zend_Application_Bootstrap_Exception
*/
public function run()
{
$front = $this->getResource('FrontController');
$default = $front->getDefaultModule();
if (null === $front->getControllerDirectory($default)) {
throw new Zend_Application_Bootstrap_Exception(
'No default controller directory registered with front controller'
);
}
$front->setParam('bootstrap', $this);
$response = $front->dispatch();
if ($front->returnResponse()) {
return $response;
}
}
/**
* Set module resource loader
*
* @param Zend_Loader_Autoloader_Resource $loader
* @return Zend_Application_Module_Bootstrap
*/
public function setResourceLoader(Zend_Loader_Autoloader_Resource $loader)
{
$this->_resourceLoader = $loader;
return $this;
}
/**
* Retrieve module resource loader
*
* @return Zend_Loader_Autoloader_Resource
*/
public function getResourceLoader()
{
if ((null === $this->_resourceLoader)
&& (false !== ($namespace = $this->getAppNamespace()))
) {
$r = new ReflectionClass($this);
$path = $r->getFileName();
$this->setResourceLoader(new Zend_Application_Module_Autoloader(array(
'namespace' => $namespace,
'basePath' => dirname($path),
)));
}
return $this->_resourceLoader;
}
/**
* Get application namespace (used for module autoloading)
*
* @return string
*/
public function getAppNamespace()
{
return $this->_appNamespace;
}
/**
* Set application namespace (for module autoloading)
*
* @param string
* @return Zend_Application_Bootstrap_Bootstrap
*/
public function setAppNamespace($value)
{
$this->_appNamespace = (string) $value;
return $this;
}
}

View File

@ -1,770 +0,0 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Application
* @subpackage Bootstrap
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BootstrapAbstract.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Abstract base class for bootstrap classes
*
* @uses Zend_Application_Bootstrap_Bootstrapper
* @uses Zend_Application_Bootstrap_ResourceBootstrapper
* @category Zend
* @package Zend_Application
* @subpackage Bootstrap
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Application_Bootstrap_BootstrapAbstract
implements Zend_Application_Bootstrap_Bootstrapper,
Zend_Application_Bootstrap_ResourceBootstrapper
{
/**
* @var Zend_Application|Zend_Application_Bootstrap_Bootstrapper
*/
protected $_application;
/**
* @var array Internal resource methods (resource/method pairs)
*/
protected $_classResources;
/**
* @var object Resource container
*/
protected $_container;
/**
* @var string
*/
protected $_environment;
/**
* Flattened (lowercase) option keys used for lookups
*
* @var array
*/
protected $_optionKeys = array();
/**
* @var array
*/
protected $_options = array();
/**
* @var Zend_Loader_PluginLoader_Interface
*/
protected $_pluginLoader;
/**
* @var array Class-based resource plugins
*/
protected $_pluginResources = array();
/**
* @var array Initializers that have been run
*/
protected $_run = array();
/**
* @var array Initializers that have been started but not yet completed (circular dependency detection)
*/
protected $_started = array();
/**
* Constructor
*
* Sets application object, initializes options, and prepares list of
* initializer methods.
*
* @param Zend_Application|Zend_Application_Bootstrap_Bootstrapper $application
* @return void
* @throws Zend_Application_Bootstrap_Exception When invalid application is provided
*/
public function __construct($application)
{
$this->setApplication($application);
$options = $application->getOptions();
$this->setOptions($options);
}
/**
* Set class state
*
* @param array $options
* @return Zend_Application_Bootstrap_BootstrapAbstract
*/
public function setOptions(array $options)
{
$this->_options = $this->mergeOptions($this->_options, $options);
$options = array_change_key_case($options, CASE_LOWER);
$this->_optionKeys = array_merge($this->_optionKeys, array_keys($options));
$methods = get_class_methods($this);
foreach ($methods as $key => $method) {
$methods[$key] = strtolower($method);
}
if (array_key_exists('pluginpaths', $options)) {
$pluginLoader = $this->getPluginLoader();
foreach ($options['pluginpaths'] as $prefix => $path) {
$pluginLoader->addPrefixPath($prefix, $path);
}
unset($options['pluginpaths']);
}
foreach ($options as $key => $value) {
$method = 'set' . strtolower($key);
if (in_array($method, $methods)) {
$this->$method($value);
} elseif ('resources' == $key) {
foreach ($value as $resource => $resourceOptions) {
$this->registerPluginResource($resource, $resourceOptions);
}
}
}
return $this;
}
/**
* Get current options from bootstrap
*
* @return array
*/
public function getOptions()
{
return $this->_options;
}
/**
* Is an option present?
*
* @param string $key
* @return bool
*/
public function hasOption($key)
{
return in_array(strtolower($key), $this->_optionKeys);
}
/**
* Retrieve a single option
*
* @param string $key
* @return mixed
*/
public function getOption($key)
{
if ($this->hasOption($key)) {
$options = $this->getOptions();
$options = array_change_key_case($options, CASE_LOWER);
return $options[strtolower($key)];
}
return null;
}
/**
* Merge options recursively
*
* @param array $array1
* @param mixed $array2
* @return array
*/
public function mergeOptions(array $array1, $array2 = null)
{
if (is_array($array2)) {
foreach ($array2 as $key => $val) {
if (is_array($array2[$key])) {
$array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key]))
? $this->mergeOptions($array1[$key], $array2[$key])
: $array2[$key];
} else {
$array1[$key] = $val;
}
}
}
return $array1;
}
/**
* Get class resources (as resource/method pairs)
*
* Uses get_class_methods() by default, reflection on prior to 5.2.6,
* as a bug prevents the usage of get_class_methods() there.
*
* @return array
*/
public function getClassResources()
{
if (null === $this->_classResources) {
if (version_compare(PHP_VERSION, '5.2.6') === -1) {
$class = new ReflectionObject($this);
$classMethods = $class->getMethods();
$methodNames = array();
foreach ($classMethods as $method) {
$methodNames[] = $method->getName();
}
} else {
$methodNames = get_class_methods($this);
}
$this->_classResources = array();
foreach ($methodNames as $method) {
if (5 < strlen($method) && '_init' === substr($method, 0, 5)) {
$this->_classResources[strtolower(substr($method, 5))] = $method;
}
}
}
return $this->_classResources;
}
/**
* Get class resource names
*
* @return array
*/
public function getClassResourceNames()
{
$resources = $this->getClassResources();
return array_keys($resources);
}
/**
* Register a new resource plugin
*
* @param string|Zend_Application_Resource_Resource $resource
* @param mixed $options
* @return Zend_Application_Bootstrap_BootstrapAbstract
* @throws Zend_Application_Bootstrap_Exception When invalid resource is provided
*/
public function registerPluginResource($resource, $options = null)
{
if ($resource instanceof Zend_Application_Resource_Resource) {
$resource->setBootstrap($this);
$pluginName = $this->_resolvePluginResourceName($resource);
$this->_pluginResources[$pluginName] = $resource;
return $this;
}
if (!is_string($resource)) {
throw new Zend_Application_Bootstrap_Exception('Invalid resource provided to ' . __METHOD__);
}
$this->_pluginResources[$resource] = $options;
return $this;
}
/**
* Unregister a resource from the bootstrap
*
* @param string|Zend_Application_Resource_Resource $resource
* @return Zend_Application_Bootstrap_BootstrapAbstract
* @throws Zend_Application_Bootstrap_Exception When unknown resource type is provided
*/
public function unregisterPluginResource($resource)
{
if ($resource instanceof Zend_Application_Resource_Resource) {
if ($index = array_search($resource, $this->_pluginResources, true)) {
unset($this->_pluginResources[$index]);
}
return $this;
}
if (!is_string($resource)) {
throw new Zend_Application_Bootstrap_Exception('Unknown resource type provided to ' . __METHOD__);
}
$resource = strtolower($resource);
if (array_key_exists($resource, $this->_pluginResources)) {
unset($this->_pluginResources[$resource]);
}
return $this;
}
/**
* Is the requested plugin resource registered?
*
* @param string $resource
* @return bool
*/
public function hasPluginResource($resource)
{
return (null !== $this->getPluginResource($resource));
}
/**
* Get a registered plugin resource
*
* @param string $resourceName
* @return Zend_Application_Resource_Resource
*/
public function getPluginResource($resource)
{
if (array_key_exists(strtolower($resource), $this->_pluginResources)) {
$resource = strtolower($resource);
if (!$this->_pluginResources[$resource] instanceof Zend_Application_Resource_Resource) {
$resourceName = $this->_loadPluginResource($resource, $this->_pluginResources[$resource]);
if (!$resourceName) {
throw new Zend_Application_Bootstrap_Exception(sprintf('Unable to resolve plugin "%s"; no corresponding plugin with that name', $resource));
}
$resource = $resourceName;
}
return $this->_pluginResources[$resource];
}
foreach ($this->_pluginResources as $plugin => $spec) {
if ($spec instanceof Zend_Application_Resource_Resource) {
$pluginName = $this->_resolvePluginResourceName($spec);
if (0 === strcasecmp($resource, $pluginName)) {
unset($this->_pluginResources[$plugin]);
$this->_pluginResources[$pluginName] = $spec;
return $spec;
}
continue;
}
if (false !== $pluginName = $this->_loadPluginResource($plugin, $spec)) {
if (0 === strcasecmp($resource, $pluginName)) {
return $this->_pluginResources[$pluginName];
}
continue;
}
if (class_exists($plugin)) { //@SEE ZF-7550
$spec = (array) $spec;
$spec['bootstrap'] = $this;
$instance = new $plugin($spec);
$pluginName = $this->_resolvePluginResourceName($instance);
unset($this->_pluginResources[$plugin]);
$this->_pluginResources[$pluginName] = $instance;
if (0 === strcasecmp($resource, $pluginName)) {
return $instance;
}
}
}
return null;
}
/**
* Retrieve all plugin resources
*
* @return array
*/
public function getPluginResources()
{
foreach (array_keys($this->_pluginResources) as $resource) {
$this->getPluginResource($resource);
}
return $this->_pluginResources;
}
/**
* Retrieve plugin resource names
*
* @return array
*/
public function getPluginResourceNames()
{
$this->getPluginResources();
return array_keys($this->_pluginResources);
}
/**
* Set plugin loader for loading resources
*
* @param Zend_Loader_PluginLoader_Interface $loader
* @return Zend_Application_Bootstrap_BootstrapAbstract
*/
public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader)
{
$this->_pluginLoader = $loader;
return $this;
}
/**
* Get the plugin loader for resources
*
* @return Zend_Loader_PluginLoader_Interface
*/
public function getPluginLoader()
{
if ($this->_pluginLoader === null) {
$options = array(
'Zend_Application_Resource' => 'Zend/Application/Resource',
'ZendX_Application_Resource' => 'ZendX/Application/Resource'
);
$this->_pluginLoader = new Zend_Loader_PluginLoader($options);
}
return $this->_pluginLoader;
}
/**
* Set application/parent bootstrap
*
* @param Zend_Application|Zend_Application_Bootstrap_Bootstrapper $application
* @return Zend_Application_Bootstrap_BootstrapAbstract
*/
public function setApplication($application)
{
if (($application instanceof Zend_Application)
|| ($application instanceof Zend_Application_Bootstrap_Bootstrapper)
) {
if ($application === $this) {
throw new Zend_Application_Bootstrap_Exception('Cannot set application to same object; creates recursion');
}
$this->_application = $application;
} else {
throw new Zend_Application_Bootstrap_Exception('Invalid application provided to bootstrap constructor (received "' . get_class($application) . '" instance)');
}
return $this;
}
/**
* Retrieve parent application instance
*
* @return Zend_Application|Zend_Application_Bootstrap_Bootstrapper
*/
public function getApplication()
{
return $this->_application;
}
/**
* Retrieve application environment
*
* @return string
*/
public function getEnvironment()
{
if (null === $this->_environment) {
$this->_environment = $this->getApplication()->getEnvironment();
}
return $this->_environment;
}
/**
* Set resource container
*
* By default, if a resource callback has a non-null return value, this
* value will be stored in a container using the resource name as the
* key.
*
* Containers must be objects, and must allow setting public properties.
*
* @param object $container
* @return Zend_Application_Bootstrap_BootstrapAbstract
*/
public function setContainer($container)
{
if (!is_object($container)) {
throw new Zend_Application_Bootstrap_Exception('Resource containers must be objects');
}
$this->_container = $container;
return $this;
}
/**
* Retrieve resource container
*
* @return object
*/
public function getContainer()
{
if (null === $this->_container) {
$this->setContainer(new Zend_Registry());
}
return $this->_container;
}
/**
* Determine if a resource has been stored in the container
*
* During bootstrap resource initialization, you may return a value. If
* you do, it will be stored in the {@link setContainer() container}.
* You can use this method to determine if a value was stored.
*
* @param string $name
* @return bool
*/
public function hasResource($name)
{
$resource = strtolower($name);
$container = $this->getContainer();
return isset($container->{$resource});
}
/**
* Retrieve a resource from the container
*
* During bootstrap resource initialization, you may return a value. If
* you do, it will be stored in the {@link setContainer() container}.
* You can use this method to retrieve that value.
*
* If no value was returned, this will return a null value.
*
* @param string $name
* @return null|mixed
*/
public function getResource($name)
{
$resource = strtolower($name);
$container = $this->getContainer();
if ($this->hasResource($resource)) {
return $container->{$resource};
}
return null;
}
/**
* Implement PHP's magic to retrieve a ressource
* in the bootstrap
*
* @param string $prop
* @return null|mixed
*/
public function __get($prop)
{
return $this->getResource($prop);
}
/**
* Implement PHP's magic to ask for the
* existence of a ressource in the bootstrap
*
* @param string $prop
* @return bool
*/
public function __isset($prop)
{
return $this->hasResource($prop);
}
/**
* Bootstrap individual, all, or multiple resources
*
* Marked as final to prevent issues when subclassing and naming the
* child class 'Bootstrap' (in which case, overriding this method
* would result in it being treated as a constructor).
*
* If you need to override this functionality, override the
* {@link _bootstrap()} method.
*
* @param null|string|array $resource
* @return Zend_Application_Bootstrap_BootstrapAbstract
* @throws Zend_Application_Bootstrap_Exception When invalid argument was passed
*/
final public function bootstrap($resource = null)
{
$this->_bootstrap($resource);
return $this;
}
/**
* Overloading: intercept calls to bootstrap<resourcename>() methods
*
* @param string $method
* @param array $args
* @return void
* @throws Zend_Application_Bootstrap_Exception On invalid method name
*/
public function __call($method, $args)
{
if (9 < strlen($method) && 'bootstrap' === substr($method, 0, 9)) {
$resource = substr($method, 9);
return $this->bootstrap($resource);
}
throw new Zend_Application_Bootstrap_Exception('Invalid method "' . $method . '"');
}
/**
* Bootstrap implementation
*
* This method may be overridden to provide custom bootstrapping logic.
* It is the sole method called by {@link bootstrap()}.
*
* @param null|string|array $resource
* @return void
* @throws Zend_Application_Bootstrap_Exception When invalid argument was passed
*/
protected function _bootstrap($resource = null)
{
if (null === $resource) {
foreach ($this->getClassResourceNames() as $resource) {
$this->_executeResource($resource);
}
foreach ($this->getPluginResourceNames() as $resource) {
$this->_executeResource($resource);
}
} elseif (is_string($resource)) {
$this->_executeResource($resource);
} elseif (is_array($resource)) {
foreach ($resource as $r) {
$this->_executeResource($r);
}
} else {
throw new Zend_Application_Bootstrap_Exception('Invalid argument passed to ' . __METHOD__);
}
}
/**
* Execute a resource
*
* Checks to see if the resource has already been run. If not, it searches
* first to see if a local method matches the resource, and executes that.
* If not, it checks to see if a plugin resource matches, and executes that
* if found.
*
* Finally, if not found, it throws an exception.
*
* @param string $resource
* @return void
* @throws Zend_Application_Bootstrap_Exception When resource not found
*/
protected function _executeResource($resource)
{
$resourceName = strtolower($resource);
if (in_array($resourceName, $this->_run)) {
return;
}
if (isset($this->_started[$resourceName]) && $this->_started[$resourceName]) {
throw new Zend_Application_Bootstrap_Exception('Circular resource dependency detected');
}
$classResources = $this->getClassResources();
if (array_key_exists($resourceName, $classResources)) {
$this->_started[$resourceName] = true;
$method = $classResources[$resourceName];
$return = $this->$method();
unset($this->_started[$resourceName]);
$this->_markRun($resourceName);
if (null !== $return) {
$this->getContainer()->{$resourceName} = $return;
}
return;
}
if ($this->hasPluginResource($resource)) {
$this->_started[$resourceName] = true;
$plugin = $this->getPluginResource($resource);
$return = $plugin->init();
unset($this->_started[$resourceName]);
$this->_markRun($resourceName);
if (null !== $return) {
$this->getContainer()->{$resourceName} = $return;
}
return;
}
throw new Zend_Application_Bootstrap_Exception('Resource matching "' . $resource . '" not found');
}
/**
* Load a plugin resource
*
* @param string $resource
* @param array|object|null $options
* @return string|false
*/
protected function _loadPluginResource($resource, $options)
{
$options = (array) $options;
$options['bootstrap'] = $this;
$className = $this->getPluginLoader()->load(strtolower($resource), false);
if (!$className) {
return false;
}
$instance = new $className($options);
unset($this->_pluginResources[$resource]);
if (isset($instance->_explicitType)) {
$resource = $instance->_explicitType;
}
$resource = strtolower($resource);
$this->_pluginResources[$resource] = $instance;
return $resource;
}
/**
* Mark a resource as having run
*
* @param string $resource
* @return void
*/
protected function _markRun($resource)
{
if (!in_array($resource, $this->_run)) {
$this->_run[] = $resource;
}
}
/**
* Resolve a plugin resource name
*
* Uses, in order of preference
* - $_explicitType property of resource
* - Short name of resource (if a matching prefix path is found)
* - class name (if none of the above are true)
*
* The name is then cast to lowercase.
*
* @param Zend_Application_Resource_Resource $resource
* @return string
*/
protected function _resolvePluginResourceName($resource)
{
if (isset($resource->_explicitType)) {
$pluginName = $resource->_explicitType;
} else {
$className = get_class($resource);
$pluginName = $className;
$loader = $this->getPluginLoader();
foreach ($loader->getPaths() as $prefix => $paths) {
if (0 === strpos($className, $prefix)) {
$pluginName = substr($className, strlen($prefix));
$pluginName = trim($pluginName, '_');
break;
}
}
}
$pluginName = strtolower($pluginName);
return $pluginName;
}
}

Some files were not shown because too many files have changed in this diff Show More