Merge branch '3.6' of github.com:alchemy-fr/Phraseanet into 3.6

This commit is contained in:
jygaulier
2012-01-02 11:59:07 +01:00
418 changed files with 10286 additions and 9531 deletions

3
.gitmodules vendored
View File

@@ -63,3 +63,6 @@
url = https://github.com/wavded/humane-js.git url = https://github.com/wavded/humane-js.git
[submodule "www/include/vendor/qunit"]
path = www/include/vendor/qunit
url = git://github.com/jquery/qunit.git

View File

@@ -15,7 +15,7 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
require_once dirname(__FILE__) . "/../lib/bootstrap.php"; require_once __DIR__ . "/../lib/bootstrap.php";
$registry = registry::get_instance(); $registry = registry::get_instance();
require($registry->get('GV_RootPath') . "lib/classes/deprecated/getargs.php"); // le parser d'arguments de la ligne de commande require($registry->get('GV_RootPath') . "lib/classes/deprecated/getargs.php"); // le parser d'arguments de la ligne de commande

View File

@@ -27,7 +27,9 @@ require_once dirname(__FILE__) . '/../lib/classes/bootstrap.class.php';
try try
{ {
bootstrap::register_autoloads(); \bootstrap::register_autoloads();
$Core = \bootstrap::getCore();
$app = new Application(" $app = new Application("
_____ _ _ _____ _____ ______ _ _ ______ _______ _____ _ _ _____ _____ ______ _ _ ______ _______
@@ -45,7 +47,8 @@ try
This program comes with ABSOLUTELY NO WARRANTY. This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it This is free software, and you are welcome to redistribute it
under certain conditions; type `about:license' for details.\n\n" under certain conditions; type `about:license' for details.\n\n"
. ' KONSOLE KOMMANDER', GV_version . ' ' . GV_version_name); . ' KONSOLE KOMMANDER', \Alchemy\Phrasea\Core\Version::getName()
. ' ' . \Alchemy\Phrasea\Core\Version::getNumber());
$app->add(new module_console_aboutAuthors('about:authors')); $app->add(new module_console_aboutAuthors('about:authors'));
$app->add(new module_console_aboutLicense('about:license')); $app->add(new module_console_aboutLicense('about:license'));

View File

@@ -28,6 +28,7 @@ require_once dirname(__FILE__) . '/../lib/Alchemy/Phrasea/Core/Service/Doctrine.
try try
{ {
$doctrineConf = array();
$doctrine = new Phrasea\Core\Service\Doctrine(); $doctrine = new Phrasea\Core\Service\Doctrine();
$app = new Application("Phraseanet Doctrine Console", $doctrine->getVersion()); $app = new Application("Phraseanet Doctrine Console", $doctrine->getVersion());

View File

@@ -15,7 +15,7 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
require_once dirname(__FILE__) . "/../lib/bootstrap.php"; require_once __DIR__ . "/../lib/bootstrap.php";
define('DOCPERDIR', 100); define('DOCPERDIR', 100);

View File

@@ -1,6 +1,6 @@
<?php <?php
include dirname(__FILE__) . '/../lib/bootstrap.php'; include __DIR__ . '/../lib/bootstrap.php';
define('FREQ_THRESHOLD', 10); define('FREQ_THRESHOLD', 10);
define('SUGGEST_DEBUG', 0); define('SUGGEST_DEBUG', 0);

View File

@@ -18,7 +18,7 @@ define('USR_ID', 4);
set_time_limit(300); set_time_limit(300);
require(dirname(__FILE__) . "/../lib/bootstrap.php"); require(__DIR__ . "/../lib/bootstrap.php");
phrasea::headers(); phrasea::headers();
$registry = registry::get_instance(); $registry = registry::get_instance();

View File

@@ -18,6 +18,7 @@ rewrite ^/prod/records/movecollection/.*$ /prod/router.php last;
rewrite ^/prod/bridge/.*$ /prod/router.php last; rewrite ^/prod/bridge/.*$ /prod/router.php last;
rewrite ^/prod/feeds/.*$ /prod/router.php last; rewrite ^/prod/feeds/.*$ /prod/router.php last;
rewrite ^/prod/tooltip/.*$ /prod/router.php last; rewrite ^/prod/tooltip/.*$ /prod/router.php last;
rewrite ^/prod/printer/.*$ /prod/router.php last;
rewrite ^/prod/baskets/.*$ /prod/router.php last; rewrite ^/prod/baskets/.*$ /prod/router.php last;
rewrite ^/prod/story/.*$ /prod/router.php last; rewrite ^/prod/story/.*$ /prod/router.php last;
rewrite ^/prod/WorkZone/.*$ /prod/router.php last; rewrite ^/prod/WorkZone/.*$ /prod/router.php last;

View File

@@ -32,6 +32,8 @@ return call_user_func(function()
$app = new Silex\Application(); $app = new Silex\Application();
$app["Core"] = bootstrap::getCore();
$app["appbox"] = appbox::get_instance(); $app["appbox"] = appbox::get_instance();
/** /**
@@ -68,7 +70,7 @@ return call_user_func(function()
*/ */
$app['api'] = function () use ($app) $app['api'] = function () use ($app)
{ {
return new API_V1_adapter(false, $app["appbox"]); return new API_V1_adapter(false, $app["appbox"], $app["Core"]);
}; };

View File

@@ -20,7 +20,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func( return call_user_func(
function() function()
{ {
@@ -30,17 +29,29 @@ return call_user_func(
$app = new Silex\Application(); $app = new Silex\Application();
$app->get('/', function () use ($session, $appbox) $app['Core'] = bootstrap::getCore();
$app->get('/', function (Silex\Application $app) use ($session, $appbox)
{ {
User_Adapter::updateClientInfos((6)); User_Adapter::updateClientInfos((6));
$basket_collection = new basketCollection($appbox, $session->get_usr_id());
$em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$basket_collection = $repository->findActiveByUser(
$app['Core']->getAuthenticatedUser()
);
$twig = new supertwig(); $twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br')); $twig->addFilter(array('nl2br' => 'nl2br'));
$browser = Browser::getInstance(); $browser = Browser::getInstance();
$template = 'lightbox/index.twig'; $template = 'lightbox/index.twig';
if (!$browser->isNewGeneration() && !$browser->isMobile()) if (!$browser->isNewGeneration() && !$browser->isMobile())
{
$template = 'lightbox/IE6/index.twig'; $template = 'lightbox/IE6/index.twig';
}
$output = $twig->render($template, array( $output = $twig->render($template, array(
'baskets_collection' => $basket_collection, 'baskets_collection' => $basket_collection,
@@ -55,7 +66,7 @@ return call_user_func(
} }
); );
$app->get('/ajax/NOTE_FORM/{sselcont_id}/', function($sselcont_id) use ($session, $appbox) $app->get('/ajax/NOTE_FORM/{sselcont_id}/', function(Silex\Application $app, $sselcont_id) use ($session, $appbox)
{ {
$browser = Browser::getInstance(); $browser = Browser::getInstance();
if (!$browser->isMobile()) if (!$browser->isMobile())
@@ -63,7 +74,14 @@ return call_user_func(
$twig = new supertwig(); $twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br')); $twig->addFilter(array('nl2br' => 'nl2br'));
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$em = $app['Core']->getEntityManager();
/* @var $repository \Repositories\BasketElementRepository */
$repository = $em->getRepository('\Entities\BasketElement');
$basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
$template = '/lightbox/note_form.twig'; $template = '/lightbox/note_form.twig';
$output = $twig->render($template, array('basket_element' => $basket_element, 'module_name' => '')); $output = $twig->render($template, array('basket_element' => $basket_element, 'module_name' => ''));
@@ -71,20 +89,25 @@ return call_user_func(
} }
)->assert('sselcont_id', '\d+'); )->assert('sselcont_id', '\d+');
$app->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function($sselcont_id) $app->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function(Silex\Application $app, $sselcont_id)
{ {
$twig = new supertwig(); $twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets')); $twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets'));
$browser = Browser::getInstance(); $browser = Browser::getInstance();
$em = $app['Core']->getEntityManager();
/* @var $repository \Repositories\BasketElementRepository */
$repository = $em->getRepository('\Entities\BasketElement');
$BasketElement = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
if ($browser->isMobile()) if ($browser->isMobile())
{ {
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$output = $twig->render('lightbox/basket_element.twig', array( $output = $twig->render('lightbox/basket_element.twig', array(
'basket_element' => $basket_element, 'basket_element' => $BasketElement,
'module_name' => $basket_element->get_record()->get_title() 'module_name' => $BasketElement->getRecord()->get_title()
) )
); );
@@ -107,19 +130,19 @@ return call_user_func(
$appbox = appbox::get_instance(); $appbox = appbox::get_instance();
$usr_id = $appbox->get_session()->get_usr_id(); $usr_id = $appbox->get_session()->get_usr_id();
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$basket = basket_adapter::getInstance($appbox, $basket_element->get_ssel_id(), $usr_id); $Basket = $BasketElement->getBasket();
$ret = array(); $ret = array();
$ret['number'] = $basket_element->get_record()->get_number(); $ret['number'] = $BasketElement->getRecord()->get_number();
$ret['title'] = $basket_element->get_record()->get_title(); $ret['title'] = $BasketElement->getRecord()->get_title();
$ret['preview'] = $twig->render($template_preview, array('record' => $basket_element->get_record(), 'not_wrapped' => true)); $ret['preview'] = $twig->render($template_preview, array('record' => $BasketElement->getRecord(), 'not_wrapped' => true));
$ret['options_html'] = $twig->render($template_options, array('basket_element' => $basket_element)); $ret['options_html'] = $twig->render($template_options, array('basket_element' => $BasketElement));
$ret['agreement_html'] = $twig->render($template_agreement, array('basket' => $basket, 'basket_element' => $basket_element)); $ret['agreement_html'] = $twig->render($template_agreement, array('basket' => $Basket, 'basket_element' => $BasketElement));
$ret['selector_html'] = $twig->render($template_selector, array('basket_element' => $basket_element)); $ret['selector_html'] = $twig->render($template_selector, array('basket_element' => $BasketElement));
$ret['note_html'] = $twig->render($template_note, array('basket_element' => $basket_element)); $ret['note_html'] = $twig->render($template_note, array('basket_element' => $BasketElement));
$ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $basket_element->get_record())); $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $BasketElement->getRecord()));
$output = p4string::jsonencode($ret); $output = p4string::jsonencode($ret);
return new Response($output, 200, array('Content-Type' => 'application/json')); return new Response($output, 200, array('Content-Type' => 'application/json'));
@@ -130,7 +153,7 @@ return call_user_func(
$app->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function($entry_id, $item_id) $app->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function(Silex\Application $app, $entry_id, $item_id)
{ {
$twig = new supertwig(); $twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets')); $twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets'));
@@ -153,13 +176,13 @@ return call_user_func(
} }
else else
{ {
$template_options = 'lightbox/sc_options_box.twig'; $template_options = 'lightbox/feed_options_box.twig';
$template_preview = 'common/preview.html'; $template_preview = 'common/preview.html';
$template_caption = 'common/caption.html'; $template_caption = 'common/caption.html';
if (!$browser->isNewGeneration()) if (!$browser->isNewGeneration())
{ {
$template_options = 'lightbox/IE6/sc_options_box.twig'; $template_options = 'lightbox/IE6/feed_options_box.twig';
} }
$usr_id = $appbox->get_session()->get_usr_id(); $usr_id = $appbox->get_session()->get_usr_id();
@@ -168,7 +191,7 @@ return call_user_func(
$ret['title'] = $item->get_record()->get_title(); $ret['title'] = $item->get_record()->get_title();
$ret['preview'] = $twig->render($template_preview, array('record' => $item->get_record(), 'not_wrapped' => true)); $ret['preview'] = $twig->render($template_preview, array('record' => $item->get_record(), 'not_wrapped' => true));
$ret['options_html'] = $twig->render($template_options, array('basket_element' => $item)); $ret['options_html'] = $twig->render($template_options, array('feed_element' => $item));
$ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $item->get_record())); $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $item->get_record()));
@@ -182,20 +205,25 @@ return call_user_func(
} }
)->assert('entry_id', '\d+')->assert('item_id', '\d+'); )->assert('entry_id', '\d+')->assert('item_id', '\d+');
$app->get('/validate/{ssel_id}/', function ($ssel_id) use ($session, $appbox) $app->get('/validate/{ssel_id}/', function (Silex\Application $app, $ssel_id) use ($session, $appbox)
{ {
User_Adapter::updateClientInfos((6)); User_Adapter::updateClientInfos((6));
$browser = Browser::getInstance(); $browser = Browser::getInstance();
$basket_collection = new basketCollection($appbox, $session->get_usr_id()); $em = $app['Core']->getEntityManager();
$basket = basket_adapter::getInstance($appbox, $ssel_id, $session->get_usr_id()); $repository = $em->getRepository('\Entities\Basket');
if ($basket->is_valid()) /* @var $repository \Repositories\BasketRepository */
{ $basket_collection = $repository->findActiveByUser(
$basket->get_first_element()->load_users_infos(); $app['Core']->getAuthenticatedUser()
} );
$basket = $repository->findUserBasket(
$ssel_id
, $app['Core']->getAuthenticatedUser()
);
$twig = new supertwig(); $twig = new supertwig();
@@ -209,7 +237,7 @@ return call_user_func(
$response = new Response($twig->render($template, array( $response = new Response($twig->render($template, array(
'baskets_collection' => $basket_collection, 'baskets_collection' => $basket_collection,
'basket' => $basket, 'basket' => $basket,
'local_title' => strip_tags($basket->get_name()), 'local_title' => strip_tags($basket->getName()),
'module' => 'lightbox', 'module' => 'lightbox',
'module_name' => _('admin::monitor: module validation') 'module_name' => _('admin::monitor: module validation')
) )
@@ -220,20 +248,25 @@ return call_user_func(
} }
)->assert('ssel_id', '\d+'); )->assert('ssel_id', '\d+');
$app->get('/compare/{ssel_id}/', function ($ssel_id) use ($session, $appbox) $app->get('/compare/{ssel_id}/', function (Silex\Application $app, $ssel_id) use ($session, $appbox)
{ {
User_Adapter::updateClientInfos((6)); User_Adapter::updateClientInfos((6));
$browser = Browser::getInstance(); $browser = Browser::getInstance();
$basket_collection = new basketCollection($appbox, $session->get_usr_id()); $em = $app['Core']->getEntityManager();
$basket = basket_adapter::getInstance($appbox, $ssel_id, $session->get_usr_id()); $repository = $em->getRepository('\Entities\Basket');
if ($basket->is_valid()) /* @var $repository \Repositories\BasketRepository */
{ $basket_collection = $repository->findActiveByUser(
$basket->get_first_element()->load_users_infos(); $app['Core']->getAuthenticatedUser()
} );
$basket = $repository->findUserBasket(
$ssel_id
, $app['Core']->getAuthenticatedUser()
);
$twig = new supertwig(); $twig = new supertwig();
@@ -247,7 +280,7 @@ return call_user_func(
$response = new Response($twig->render($template, array( $response = new Response($twig->render($template, array(
'baskets_collection' => $basket_collection, 'baskets_collection' => $basket_collection,
'basket' => $basket, 'basket' => $basket,
'local_title' => strip_tags($basket->get_name()), 'local_title' => strip_tags($basket->getName()),
'module' => 'lightbox', 'module' => 'lightbox',
'module_name' => _('admin::monitor: module validation') 'module_name' => _('admin::monitor: module validation')
) )
@@ -260,7 +293,7 @@ return call_user_func(
$app->get('/feeds/entry/{entry_id}/', function ($entry_id) use ($session, $appbox) $app->get('/feeds/entry/{entry_id}/', function (Silex\Application $app, $entry_id) use ($session, $appbox)
{ {
User_Adapter::updateClientInfos((6)); User_Adapter::updateClientInfos((6));
@@ -293,7 +326,7 @@ return call_user_func(
} }
)->assert('entry_id', '\d+'); )->assert('entry_id', '\d+');
$app->get('/ajax/LOAD_REPORT/{ssel_id}/', function($ssel_id) use ($appbox, $app) $app->get('/ajax/LOAD_REPORT/{ssel_id}/', function(Silex\Application $app, $ssel_id)
{ {
$twig = new supertwig(); $twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br')); $twig->addFilter(array('nl2br' => 'nl2br'));
@@ -302,7 +335,14 @@ return call_user_func(
$template = 'lightbox/basket_content_report.twig'; $template = 'lightbox/basket_content_report.twig';
$basket = basket_adapter::getInstance($appbox, $ssel_id, $appbox->get_session()->get_usr_id()); $em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$basket = $repository->findUserBasket(
$ssel_id
, $app['Core']->getAuthenticatedUser()
);
$response = new Response($twig->render($template, array('basket' => $basket))); $response = new Response($twig->render($template, array('basket' => $basket)));
$response->setCharset('UTF-8'); $response->setCharset('UTF-8');
@@ -311,39 +351,46 @@ return call_user_func(
} }
)->assert('ssel_id', '\d+'); )->assert('ssel_id', '\d+');
$app->post('/ajax/SET_NOTE/{sselcont_id}/', function ($sselcont_id) use ($app) $app->post('/ajax/SET_NOTE/{sselcont_id}/', function (Silex\Application $app, $sselcont_id)
{ {
$output = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees')); $output = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees'));
try
$request = $app['request'];
$note = $request->get('note');
if (is_null($note))
{ {
$request = $app['request']; Return new Response('You must provide a note value', 400);
$note = $request->get('note');
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$basket_element->set_note($note);
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$browser = Browser::getInstance();
if ($browser->isMobile())
{
$datas = $twig->render('lightbox/sc_note.twig', array('basket_element' => $basket_element));
$output = array('error' => false, 'datas' => $datas);
}
else
{
$template = 'lightbox/sc_note.twig';
$datas = $twig->render($template, array('basket_element' => $basket_element));
$output = array('error' => false, 'datas' => $datas);
}
} }
catch (Exception $e)
$em = $app['Core']->getEntityManager();
/* @var $repository \Repositories\BasketElementRepository */
$repository = $em->getRepository('\Entities\BasketElement');
$basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
$basket_element->getUserValidationDatas($app['Core']->getAuthenticatedUser())
->setNote($note);
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$browser = Browser::getInstance();
if ($browser->isMobile())
{ {
return new Response('Bad Request : ' . $e->getMessage() . $e->getFile() . $e->getLine(), 400); $datas = $twig->render('lightbox/sc_note.twig', array('basket_element' => $basket_element));
$output = array('error' => false, 'datas' => $datas);
}
else
{
$template = 'lightbox/sc_note.twig';
$datas = $twig->render($template, array('basket_element' => $basket_element));
$output = array('error' => false, 'datas' => $datas);
} }
$output = p4string::jsonencode($output); $output = p4string::jsonencode($output);
@@ -352,35 +399,56 @@ return call_user_func(
} }
)->assert('sselcont_id', '\d+'); )->assert('sselcont_id', '\d+');
$app->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function($sselcont_id) use ($app) $app->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function(Silex\Application $app, $sselcont_id)
{ {
$request = $app['request']; $request = $app['request'];
$agreement = (int) $request->get('agreement'); $agreement = $request->get('agreement');
if (is_null($agreement))
{
Return new Response('You must provide an agreement value', 400);
}
$agreement = $agreement > 0;
$ret = array( $ret = array(
'error' => true, 'error' => true,
'releasable' => false, 'releasable' => false,
'datas' => _('Erreur lors de la mise a jour des donnes ') 'datas' => _('Erreur lors de la mise a jour des donnes ')
); );
try
{
$appbox = appbox::get_instance();
$basket_element = basket_element_adapter::getInstance($sselcont_id); $user = $app['Core']->getAuthenticatedUser();
$basket_element->set_agreement($agreement); $em = $app['Core']->getEntityManager();
$basket = basket_adapter::getInstance($appbox, $basket_element->get_ssel_id(), $appbox->get_session()->get_usr_id()); $repository = $em->getRepository('\Entities\BasketElement');
$ret = array( /* @var $repository \Repositories\BasketElementRepository */
'error' => false $basket_element = $repository->findUserElement(
, 'datas' => '' $sselcont_id
, 'releasable' => $basket->is_releasable() ? _('Do you want to send your report ?') : false , $user
); );
} /* @var $basket_element \Entities\BasketElement */
catch (Exception $e) $basket_element->getUserValidationDatas($user)
->setAgreement($agreement);
$participant = $basket_element->getBasket()
->getValidation()
->getParticipant($user);
if ($participant->getIsConfirmed() === true)
{ {
return new Response('Bad Request', 400); $releasable = false;
} }
else
{
$releasable = _('Do you want to send your report ?');
}
$ret = array(
'error' => false
, 'datas' => ''
, 'releasable' => $releasable
);
$output = p4string::jsonencode($ret); $output = p4string::jsonencode($ret);
return new Response($output, 200, array('Content-Type' => 'application/json')); return new Response($output, 200, array('Content-Type' => 'application/json'));
@@ -388,24 +456,31 @@ return call_user_func(
)->assert('sselcont_id', '\d+'); )->assert('sselcont_id', '\d+');
$app->post('/ajax/SET_RELEASE/{ssel_id}/', function($ssel_id) use ($session, $appbox) $app->post('/ajax/SET_RELEASE/{ssel_id}/', function(Silex\Application $app, $ssel_id) use ($session, $appbox)
{ {
$basket = basket_adapter::getInstance($appbox, $ssel_id, $appbox->get_session()->get_usr_id());
$datas = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees')); $em = $app['Core']->getEntityManager();
try
{
$appbox->get_connection()->beginTransaction();
$basket->set_released();
$datas = array('error' => false, 'datas' => _('Envoie avec succes'));
$appbox->get_connection()->commit();
}
catch (Exception $e)
{
$appbox->get_connection()->rollBack();
return new Response('Bad Request', 400); $user = $app['Core']->getAuthenticatedUser();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$basket = $repository->findUserBasket(
$ssel_id
, $user
);
if (!$basket->getValidation())
{
Return new Response('There is no validation session attached to this basket', 400);
} }
/* @var $basket \Entities\Basket */
$participant = $basket->getValidation()->getParticipant($user);
$participant->setIsConfirmed(true);
$datas = array('error' => false, 'datas' => _('Envoie avec succes'));
$output = p4string::jsonencode($datas); $output = p4string::jsonencode($datas);
$response = new Response($output, 200, array('Content-Type' => 'application/json')); $response = new Response($output, 200, array('Content-Type' => 'application/json'));

View File

@@ -33,6 +33,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return call_user_func(function() return call_user_func(function()
{ {
$app = new Silex\Application(); $app = new Silex\Application();
$app['Core'] = bootstrap::getCore();
$app->register(new Silex\Provider\ValidatorServiceProvider(), array( $app->register(new Silex\Provider\ValidatorServiceProvider(), array(
'validator.class_path' => __DIR__ . '/../../../../lib/vendor/symfony/src', 'validator.class_path' => __DIR__ . '/../../../../lib/vendor/symfony/src',

View File

@@ -29,6 +29,8 @@ return call_user_func(
$session = $appbox->get_session(); $session = $appbox->get_session();
$app = new Silex\Application(); $app = new Silex\Application();
$app['Core'] = bootstrap::getCore();
$deliver_content = function(Session_Handler $session, record_adapter $record, $subdef, $watermark, $stamp, $app) $deliver_content = function(Session_Handler $session, record_adapter $record, $subdef, $watermark, $stamp, $app)
@@ -112,11 +114,18 @@ return call_user_func(
if ($watermark) if ($watermark)
{ {
if (basket_element_adapter::is_in_validation_session($record, $user))
$em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\BasketElement');
/* @var $repository \Repositories\BasketElementRepository */
if ($repository->findReceivedValidationElementsByRecord($record, $user)->count() > 0)
{ {
$watermark = false; $watermark = false;
} }
elseif (basket_element_adapter::has_been_received($record, $user)) elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0)
{ {
$watermark = false; $watermark = false;
} }
@@ -159,14 +168,20 @@ return call_user_func(
if ($watermark) if ($watermark)
{ {
if (basket_element_adapter::is_in_validation_session($record, $user))
$em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\BasketElement');
if ($repository->findReceivedValidationElementsByRecord($record, $user)->count() > 0)
{ {
$watermark = false; $watermark = false;
} }
elseif (basket_element_adapter::has_been_received($record, $user)) elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0)
{ {
$watermark = false; $watermark = false;
} }
} }
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app); return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);

View File

@@ -44,6 +44,7 @@ return call_user_func(function()
$app->mount('/records/edit', new Controller\Edit()); $app->mount('/records/edit', new Controller\Edit());
$app->mount('/records/movecollection', new Controller\MoveCollection()); $app->mount('/records/movecollection', new Controller\MoveCollection());
$app->mount('/bridge/', new Controller\Bridge()); $app->mount('/bridge/', new Controller\Bridge());
$app->mount('/printer/', new Controller\Printer());
$app->mount('/feeds', new Controller\Feed()); $app->mount('/feeds', new Controller\Feed());
$app->mount('/tooltip', new Controller\Tooltip()); $app->mount('/tooltip', new Controller\Tooltip());
$app->mount('/', new Controller\Root()); $app->mount('/', new Controller\Root());

View File

@@ -45,7 +45,7 @@ return call_user_func(function()
$app->get('robots.txt', function() use ($app) $app->get('robots.txt', function() use ($app)
{ {
require dirname(__FILE__) . "/../lib/bootstrap.php"; require __DIR__ . "/../lib/bootstrap.php";
$appbox = appbox::get_instance(); $appbox = appbox::get_instance();
$registry = $appbox->get_registry(); $registry = $appbox->get_registry();

View File

@@ -15,6 +15,7 @@ use Silex\Application;
use Alchemy\Phrasea\Controller\Setup as Controller; use Alchemy\Phrasea\Controller\Setup as Controller;
use Alchemy\Phrasea\Controller\Utils as ControllerUtils; use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
require_once __DIR__ . '/../../../bootstrap.php';
/** /**
* *
* @package * @package
@@ -25,6 +26,8 @@ use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
return call_user_func(function() return call_user_func(function()
{ {
$app = new Silex\Application(); $app = new Silex\Application();
$app['Core'] = bootstrap::getCore();
$app['install'] = false; $app['install'] = false;
$app['upgrade'] = false; $app['upgrade'] = false;

View File

@@ -39,8 +39,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/', function() use ($app) $controllers->post('/rights/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$template = 'admin/editusers.twig'; $template = 'admin/editusers.twig';
$twig = new \supertwig(); $twig = new \supertwig();
@@ -55,8 +54,7 @@ class Users implements ControllerProviderInterface
$controllers->get('/rights/', function() use ($app) $controllers->get('/rights/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$template = 'admin/editusers.twig'; $template = 'admin/editusers.twig';
$twig = new \supertwig(); $twig = new \supertwig();
@@ -71,11 +69,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/delete/', function() use ($app) $controllers->post('/delete/', function() use ($app)
{ {
$request = $app['request']; $module = new UserHelper\Edit($app['Core']);
$module = new UserHelper\Edit($request);
$module->delete_users(); $module->delete_users();
return $app->redirect('/admin/users/search/'); return $app->redirect('/admin/users/search/');
@@ -88,8 +82,7 @@ class Users implements ControllerProviderInterface
try try
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$rights->apply_rights(); $rights->apply_rights();
$rights->apply_infos(); $rights->apply_infos();
@@ -110,8 +103,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/quotas/', function() use ($app) $controllers->post('/rights/quotas/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$template = 'admin/editusers_quotas.twig'; $template = 'admin/editusers_quotas.twig';
$twig = new \supertwig(); $twig = new \supertwig();
@@ -125,8 +117,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/quotas/apply/', function() use ($app) $controllers->post('/rights/quotas/apply/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$rights->apply_quotas(); $rights->apply_quotas();
return; return;
@@ -135,8 +126,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/time/', function() use ($app) $controllers->post('/rights/time/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$template = 'admin/editusers_timelimit.twig'; $template = 'admin/editusers_timelimit.twig';
$twig = new \supertwig(); $twig = new \supertwig();
@@ -150,8 +140,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/time/apply/', function() use ($app) $controllers->post('/rights/time/apply/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$rights->apply_time(); $rights->apply_time();
return; return;
@@ -160,8 +149,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/masks/', function() use ($app) $controllers->post('/rights/masks/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$template = 'admin/editusers_masks.twig'; $template = 'admin/editusers_masks.twig';
$twig = new \supertwig(); $twig = new \supertwig();
@@ -175,46 +163,40 @@ class Users implements ControllerProviderInterface
$controllers->post('/rights/masks/apply/', function() use ($app) $controllers->post('/rights/masks/apply/', function() use ($app)
{ {
$request = $app['request']; $rights = new UserHelper\Edit($app['Core']);
$rights = new UserHelper\Edit($request);
$rights->apply_masks(); $rights->apply_masks();
return; return;
} }
); );
$controllers->post('/search/', function() use ($app) $controllers->match('/search/', function() use ($app)
{ {
$request = $app['request']; $users = new UserHelper\Manage($app['Core']);
$users = new UserHelper\Manage($request);
$template = 'admin/users.html'; $template = 'admin/users.html';
$twig = new \supertwig(); $twig = new \supertwig();
$twig->addFilter(array('floor' => 'floor')); $twig->addFilter(array('floor' => 'floor'));
$twig->addFilter(array('getDate' => 'phraseadate::getDate')); $twig->addFilter(array('getDate' => 'phraseadate::getDate'));
return $twig->render($template, $users->search($request)); return $twig->render($template, $users->search());
} }
); );
$controllers->get('/search/', function() use ($app) $controllers->post('/apply_template/', function() use ($app)
{ {
$request = $app['request']; $users = UserHelper\Manage($app['Core']);
$users = new UserHelper\Manage($request);
$template = 'admin/users.html'; $users->apply_template();
$twig = new \supertwig(); return new Symfony\Component\HttpFoundation\RedirectResponse('/admin/users/search/');
$twig->addFilter(array('floor' => 'floor'));
$twig->addFilter(array('getDate' => 'phraseadate::getDate'));
return $twig->render($template, $users->search($request));
} }
); );
$controllers->get('/typeahead/search/', function() use ($app, $appbox) $controllers->get('/typeahead/search/', function() use ($app, $appbox)
{ {
$request = $app['request']; $request = $app['request'];
$user_query = new User_Query($appbox); $user_query = new \User_Query($appbox);
$user = User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$like_value = $request->get('term'); $like_value = $request->get('term');
@@ -258,7 +240,7 @@ class Users implements ControllerProviderInterface
try try
{ {
$request = $app['request']; $request = $app['request'];
$module = new UserHelper\Manage($request); $module = new UserHelper\Manage($app['Core']);
if ($request->get('template') == '1') if ($request->get('template') == '1')
{ {
$user = $module->create_template(); $user = $module->create_template();
@@ -285,7 +267,7 @@ class Users implements ControllerProviderInterface
$controllers->post('/export/csv/', function() use ($appbox, $app) $controllers->post('/export/csv/', function() use ($appbox, $app)
{ {
$request = $app['request']; $request = $app['request'];
$user_query = new \User_Query($appbox); $user_query = new \User_Query($appbox, $app['Core']);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$like_value = $request->get('like_value'); $like_value = $request->get('like_value');

View File

@@ -136,7 +136,7 @@ class Basket implements ControllerProviderInterface
}); });
$controllers->post( $controllers->post(
'/{basket_id}/{basket_element_id}/delete/' '/{basket_id}/delete/{basket_element_id}/'
, function(Application $app, Request $request, $basket_id, $basket_element_id) , function(Application $app, Request $request, $basket_id, $basket_element_id)
{ {
/* @var $em \Doctrine\ORM\EntityManager */ /* @var $em \Doctrine\ORM\EntityManager */
@@ -342,6 +342,61 @@ class Basket implements ControllerProviderInterface
return new RedirectResponse('/'); return new RedirectResponse('/');
} }
}); });
$controllers->post(
'/{basket_id}/stealElements/'
, function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser());
$user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */
$n = 0;
foreach ($request->get('elements') as $bask_element_id)
{
$basket_element = $em->getRepository('\Entities\BasketElement')
->findUserElement($bask_element_id, $user);
if(!$basket_element)
{
continue;
}
$basket_element->setBasket($basket);
$em->merge($basket_element);
$n++;
}
$em->merge($basket);
$em->flush();
$data = array(
'success' => true
, 'message' => sprintf(_('%d records moved'), $n)
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
});
$controllers->get('/create/', function(Application $app) $controllers->get('/create/', function(Application $app)
{ {
@@ -364,7 +419,7 @@ class Basket implements ControllerProviderInterface
$twig = new \supertwig(); $twig = new \supertwig();
$html = $twig->render('prod/basket.twig', array('basket' => $basket)); $html = $twig->render('prod/WorkZone/Basket.html.twig', array('basket' => $basket));
return new Response($html); return new Response($html);
})->assert('basket_id', '\d+'); })->assert('basket_id', '\d+');

View File

@@ -45,9 +45,9 @@ class Bridge implements ControllerProviderInterface
}; };
if (!$account->get_api()->get_connector()->is_configured()) if (!$account->get_api()->get_connector()->is_configured())
throw new \Bridge_Exception_ApiConnectorNotConfigured(); throw new \Bridge_Exception_ApiConnectorNotConfigured("Bridge API Connector is not configured");
if (!$account->get_api()->get_connector()->is_connected()) if (!$account->get_api()->get_connector()->is_connected())
throw new \Bridge_Exception_ApiConnectorNotConnected (); throw new \Bridge_Exception_ApiConnectorNotConnected ("Bridge API Connector is not connected");
return; return;
}); });
@@ -55,7 +55,7 @@ class Bridge implements ControllerProviderInterface
$controllers->post('/manager/' $controllers->post('/manager/'
, function() use ($app, $twig) , function() use ($app, $twig)
{ {
$route = new RecordHelper\Bridge($app['request']); $route = new RecordHelper\Bridge($app['Core']);
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
@@ -63,6 +63,7 @@ class Bridge implements ControllerProviderInterface
'user_accounts' => \Bridge_Account::get_accounts_by_user($appbox, $user) 'user_accounts' => \Bridge_Account::get_accounts_by_user($appbox, $user)
, 'available_apis' => \Bridge_Api::get_availables($appbox) , 'available_apis' => \Bridge_Api::get_availables($appbox)
, 'route' => $route , 'route' => $route
, 'current_account_id' => ''
); );
return new Response($twig->render('prod/actions/Bridge/index.twig', $params) return new Response($twig->render('prod/actions/Bridge/index.twig', $params)
@@ -171,7 +172,7 @@ class Bridge implements ControllerProviderInterface
$app['require_connection']($account); $app['require_connection']($account);
$elements = $account->get_api()->list_elements($type, $offset_start, $quantity); $elements = $account->get_api()->list_elements($type, $offset_start, $quantity);
$params = array( $params = array(
'action_type' => $type 'action_type' => $type
, 'adapter_action' => 'load-elements' , 'adapter_action' => 'load-elements'
@@ -274,6 +275,8 @@ class Bridge implements ControllerProviderInterface
, 'destination' => $destination , 'destination' => $destination
, 'element_type' => $element_type , 'element_type' => $element_type
, 'action' => $action , 'action' => $action
, 'constraint_errors' => null
, 'adapter_action' => $action
, 'elements' => $elements , 'elements' => $elements
, 'error_message' => $app['request']->get('error') , 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice') , 'notice_message' => $app['request']->get('notice')
@@ -420,7 +423,7 @@ class Bridge implements ControllerProviderInterface
$account = \Bridge_Account::load_account($appbox, $request->get('account_id')); $account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account); $app['require_connection']($account);
$route = new RecordHelper\Bridge($request); $route = new RecordHelper\Bridge($app['Core']);
$route->grep_records($account->get_api()->acceptable_records()); $route->grep_records($account->get_api()->acceptable_records());
$params = array( $params = array(
@@ -447,7 +450,7 @@ class Bridge implements ControllerProviderInterface
$account = \Bridge_Account::load_account($appbox, $request->get('account_id')); $account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account); $app['require_connection']($account);
$route = new RecordHelper\Bridge($request); $route = new RecordHelper\Bridge($app['Core']);
$route->grep_records($account->get_api()->acceptable_records()); $route->grep_records($account->get_api()->acceptable_records());
$connector = $account->get_api()->get_connector(); $connector = $account->get_api()->get_connector();

View File

@@ -30,9 +30,7 @@ class Edit implements ControllerProviderInterface
$controllers->post('/', function() use ($app) $controllers->post('/', function() use ($app)
{ {
$request = $app['request']; $handler = new RecordHelper\Edit($app['Core']);
$handler = new RecordHelper\Edit($request);
$handler->propose_editing(); $handler->propose_editing();
@@ -48,7 +46,7 @@ class Edit implements ControllerProviderInterface
$controllers->post('/apply/', function() use ($app) $controllers->post('/apply/', function() use ($app)
{ {
$request = $app['request']; $request = $app['request'];
$editing = new RecordHelper\Edit($request); $editing = new RecordHelper\Edit($app['Core']);
$editing->execute($request); $editing->execute($request);
$template = 'prod/actions/edit_default.twig'; $template = 'prod/actions/edit_default.twig';

View File

@@ -43,7 +43,7 @@ class Feed implements ControllerProviderInterface
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$feeds = \Feed_Collection::load_all($appbox, $user); $feeds = \Feed_Collection::load_all($appbox, $user);
$request = $app['request']; $request = $app['request'];
$publishing = new RecordHelper\Feed($request); $publishing = new RecordHelper\Feed($app['Core']);
$datas = $twig->render('prod/actions/publish/publish.html', array('publishing' => $publishing, 'feeds' => $feeds)); $datas = $twig->render('prod/actions/publish/publish.html', array('publishing' => $publishing, 'feeds' => $feeds));
@@ -71,7 +71,7 @@ class Feed implements ControllerProviderInterface
$entry = \Feed_Entry_Adapter::create($appbox, $feed, $publisher, $title, $subtitle, $author_name, $author_mail); $entry = \Feed_Entry_Adapter::create($appbox, $feed, $publisher, $title, $subtitle, $author_name, $author_mail);
$publishing = new RecordHelper\Feed($request); $publishing = new RecordHelper\Feed($app['Core']);
foreach ($publishing->get_elements() as $record) foreach ($publishing->get_elements() as $record)
{ {

View File

@@ -34,7 +34,7 @@ class MoveCollection implements ControllerProviderInterface
$controllers->post('/', function() use ($app) $controllers->post('/', function() use ($app)
{ {
$request = $app['request']; $request = $app['request'];
$move = new RecordHelper\MoveCollection($request); $move = new RecordHelper\MoveCollection($app['Core']);
$move->propose(); $move->propose();
$template = 'prod/actions/collection_default.twig'; $template = 'prod/actions/collection_default.twig';
@@ -49,7 +49,7 @@ class MoveCollection implements ControllerProviderInterface
$controllers->post('/apply/', function() use ($app) $controllers->post('/apply/', function() use ($app)
{ {
$request = $app['request']; $request = $app['request'];
$move = new RecordHelper\MoveCollection($request); $move = new RecordHelper\MoveCollection($app['Core']);
$move->execute($request); $move->execute($request);
$template = 'prod/actions/collection_submit.twig'; $template = 'prod/actions/collection_submit.twig';

View File

@@ -0,0 +1,71 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Controller\Prod;
use Silex\Application,
Silex\ControllerProviderInterface,
Silex\ControllerCollection;
use Alchemy\Phrasea\Helper\Record as RecordHelper,
Alchemy\Phrasea\Out\Module\PDF as PDFExport;
use Symfony\Component\HttpFoundation\Response;
/**
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Printer implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->post('/', function() use ($app)
{
$printer = new RecordHelper\Printer($app['Core']);
$template = 'prod/actions/printer_default.html.twig';
$twig = new \supertwig();
return $twig->render($template, array('printer' => $printer, 'message' => ''));
}
);
$controllers->post('/print.pdf', function() use ($app)
{
$printer = new RecordHelper\Printer($app['Core']);
$request = $app['request'];
$session = \Session_Handler::getInstance(\appbox::get_instance());
$layout = $request->get('lay');
foreach ($printer->get_elements() as $record)
{
$session->get_logger($record->get_databox())
->log($record, \Session_Logger::EVENT_PRINT, $layout, '');
}
$PDF = new PDFExport($printer->get_elements(), $layout);
return new Response($PDF->render(), 200, array('Content-Type' => 'application/pdf'));
}
);
return $controllers;
}
}

View File

@@ -37,7 +37,6 @@ class Root implements ControllerProviderInterface
$controllers->get('/', function(Application $app) $controllers->get('/', function(Application $app)
{ {
\User_Adapter::updateClientInfos(1); \User_Adapter::updateClientInfos(1);
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
@@ -115,11 +114,10 @@ class Root implements ControllerProviderInterface
'module_prod' => new Helper\Prod($app['Core']), 'module_prod' => new Helper\Prod($app['Core']),
'cssfile' => $cssfile, 'cssfile' => $cssfile,
'module' => 'prod', 'module' => 'prod',
'events' => \eventsmanager_broker::getInstance($appbox), 'events' => \eventsmanager_broker::getInstance($appbox, $app['Core']),
'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'), 'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'),
'GV_multiAndReport' => $registry->get('GV_multiAndReport'), 'GV_multiAndReport' => $registry->get('GV_multiAndReport'),
'GV_thesaurus' => $registry->get('GV_thesaurus'), 'GV_thesaurus' => $registry->get('GV_thesaurus'),
// 'basket_collection' => new \basketCollection($appbox, $user->get_id(), $srt),
'cgus_agreement' => \databox_cgu::askAgreement(), 'cgus_agreement' => \databox_cgu::askAgreement(),
'css' => $css, 'css' => $css,
'feeds' => $feeds, 'feeds' => $feeds,

View File

@@ -43,12 +43,9 @@ class Story implements ControllerProviderInterface
return new Response($twig->render('prod/Story/Create.html.twig', array())); return new Response($twig->render('prod/Story/Create.html.twig', array()));
}); });
$controllers->post('/', function(Application $app) $controllers->post('/', function(Application $app, Request $request)
{ {
$request = $app['request']; /* @var $request \Symfony\Component\HttpFoundation\Request */
// /* @var $request \Symfony\Component\HttpFoundation\Request */
//
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
@@ -107,7 +104,7 @@ class Story implements ControllerProviderInterface
'record_id' => $Story->get_record_id(), 'record_id' => $Story->get_record_id(),
) )
); );
$datas = $app['Core']['Serializer']->serialize($data, 'json'); $datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json')); return new Response($datas, 200, array('Content-type' => 'application/json'));
@@ -222,87 +219,6 @@ class Story implements ControllerProviderInterface
return new RedirectResponse('/'); return new RedirectResponse('/');
} }
}); });
$controllers->post(
'/{sbas_id}/{record_id}/attach/'
, function(Application $app, Request $request, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
if (!$Story->is_grouping())
throw new \Exception('You can only attach stories');
$user = $app['Core']->getAuthenticatedUser();
if (!$user->ACL()->has_right_on_base($Story->get_base_id()))
throw new \Exception_Forbidden('You do not have access to this Story');
$em = $app['Core']->getEntityManager();
$StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
$em->persist($StoryWZ);
$data = array(
'success' => true
, 'message' => _('Story attached to the WorkZone')
, 'StoryWZ' => array(
'id' => $StoryWZ->getId()
)
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/{sbas_id}/{record_id}/');
}
});
$controllers->post(
'/{sbas_id}/{record_id}/detach/'
, function(Application $app, Request $request, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
$user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager();
$repository = $em->getRepository('Entities\StoryWZ');
/* @var $repository \Repositories\StoryWZRepository */
$StoryWZ = $repository->findUserStory($user, $Story);
if (!$StoryWZ)
{
throw new \Exception_NotFound('Story not found');
}
$data = array(
'success' => true
, 'message' => _('Story detached from the WorkZone')
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
});
// $controllers->post('/{basket_id}/delete/', function(Application $app, Request $request, $basket_id) // $controllers->post('/{basket_id}/delete/', function(Application $app, Request $request, $basket_id)
// { // {
// $em = $app['Core']->getEntityManager(); // $em = $app['Core']->getEntityManager();

View File

@@ -46,11 +46,151 @@ class WorkZone implements ControllerProviderInterface
, 'srt' => $app['request']->get('sort') , 'srt' => $app['request']->get('sort')
); );
$twig->addFilter(array('get_collection_logo' => 'collection::getLogo'));
return new Response($twig->render('prod/baskets.html', $params)); return new Response($twig->render('prod/WorkZone/WorkZone.html.twig', $params));
}); });
$controllers->post(
'/attachStories/'
, function(Application $app, Request $request)
{
$user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */
$StoryWZRepo = $em->getRepository('\Entities\StoryWZ');
$alreadyFixed = $done = 0;
foreach ( explode(';', $request->get('stories')) as $element)
{
$element = explode('_', $element);
$Story = new \record_adapter($element[0], $element[1]);
if (!$Story->is_grouping())
throw new \Exception('You can only attach stories');
if (!$user->ACL()->has_access_to_base($Story->get_base_id()))
throw new \Exception_Forbidden('You do not have access to this Story');
if ($StoryWZRepo->findUserStory($user, $Story))
{
$alreadyFixed++;
continue;
}
$StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
$em->persist($StoryWZ);
$done++;
}
$em->flush();
if ($alreadyFixed === 0)
{
if ($done <= 1)
{
$message = sprintf(
_('%d Story attached to the WorkZone')
, $done
);
}
else
{
$message = sprintf(
_('%d Stories attached to the WorkZone')
, $done
);
}
}
else
{
if ($done <= 1)
{
$message = sprintf(
_('%1$d Story attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
else
{
$message = sprintf(
_('%1$d Story attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
}
$data = array(
'success' => true
, 'message' => $message
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/{sbas_id}/{record_id}/');
}
});
$controllers->post(
'/detachStory/{sbas_id}/{record_id}/'
, function(Application $app, Request $request, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
$user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\StoryWZ');
/* @var $repository \Repositories\StoryWZRepository */
$StoryWZ = $repository->findUserStory($user, $Story);
if (!$StoryWZ)
{
throw new \Exception_NotFound('Story not found');
}
$em->remove($StoryWZ);
$em->flush();
$data = array(
'success' => true
, 'message' => _('Story detached from the WorkZone')
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
});
return $controllers; return $controllers;
} }

View File

@@ -44,15 +44,21 @@ class RSSFeeds implements ControllerProviderInterface
$registry = \registry::get_instance(); $registry = \registry::get_instance();
if ($format == 'rss') if ($format == \Feed_Adapter::FORMAT_RSS)
{ {
$content = new \Feed_XML_RSS(); $content = new \Feed_XML_RSS();
} }
if ($format == 'atom')
if ($format == \Feed_Adapter::FORMAT_ATOM)
{ {
$content = new \Feed_XML_Atom(); $content = new \Feed_XML_Atom();
} }
if($format == \Feed_Adapter::FORMAT_COOLIRIS)
{
$content = new \Feed_XML_Cooliris();
}
if ($user instanceof \User_Adapter) if ($user instanceof \User_Adapter)
$link = $feed->get_user_link($registry, $user, $format, $page); $link = $feed->get_user_link($registry, $user, $format, $page);
else else
@@ -80,7 +86,7 @@ class RSSFeeds implements ControllerProviderInterface
} }
foreach ($entries->get_entries() as $entry) foreach ($entries->get_entries() as $entry)
$content->set_item($entry); $content->set_item($entry);
$render = $content->render(); $render = $content->render();
$response = new Response($render, 200, array('Content-Type' => $content->get_mimetype())); $response = new Response($render, 200, array('Content-Type' => $content->get_mimetype()));
$response->setCharset('UTF-8'); $response->setCharset('UTF-8');
@@ -164,7 +170,18 @@ class RSSFeeds implements ControllerProviderInterface
return $display_feed($feed, $format, $page); return $display_feed($feed, $format, $page);
})->assert('format', '(rss|atom)'); })->assert('format', '(rss|atom)');
$controllers->get('/cooliris/', function() use ($app, $appbox, $display_feed) {
$feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate();
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
return $display_feed($feed, \Feed_Adapter::FORMAT_COOLIRIS , $page);
});
return $controllers; return $controllers;
} }
} }

View File

@@ -20,15 +20,6 @@ use Silex\ControllerProviderInterface;
use Silex\ControllerCollection; use Silex\ControllerCollection;
date_default_timezone_set('Europe/Berlin'); date_default_timezone_set('Europe/Berlin');
require_once dirname(__FILE__) . '/../../../../version.inc';
require_once dirname(__FILE__) . '/../../../../classes/phrasea.class.php';
require_once dirname(__FILE__) . '/../../../../classes/bootstrap.class.php';
require_once dirname(__FILE__) . '/../../../../classes/cache/cacheableInterface.class.php';
require_once dirname(__FILE__) . '/../../../../classes/cache/interface.class.php';
require_once dirname(__FILE__) . '/../../../../classes/cache/nocache.class.php';
require_once dirname(__FILE__) . '/../../../../classes/cache/adapter.class.php';
require_once dirname(__FILE__) . '/../../../../classes/User/Interface.class.php';
require_once dirname(__FILE__) . '/../../../../classes/User/Adapter.class.php';
/** /**
* *
@@ -43,8 +34,6 @@ class Installer implements ControllerProviderInterface
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$app['available_languages'] = \User_Adapter::detectLanguage(new \Setup_Registry());
$controllers->get('/', function() use ($app) $controllers->get('/', function() use ($app)
{ {
$request = $app['request']; $request = $app['request'];
@@ -89,17 +78,17 @@ class Installer implements ControllerProviderInterface
} }
$ld_path = array(dirname(__FILE__) . '/../../../../templates/web'); $ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new Twig_Loader_Filesystem($ld_path); $loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new Twig_Environment($loader); $twig = new \Twig_Environment($loader);
$html = $twig->render( $html = $twig->render(
'/setup/index.twig' '/setup/index.twig'
, array_merge($constraints_coll, array( , array_merge($constraints_coll, array(
'locale' => Session_Handler::get_locale() 'locale' => Session_Handler::get_locale()
, 'available_locales' => $app['available_languages'] , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'version_number' => GV_version , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => GV_version_name , 'version_name' => $app['Core']['Version']->getName()
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/' , 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
)) ))
); );
@@ -111,12 +100,12 @@ class Installer implements ControllerProviderInterface
{ {
\phrasea::use_i18n(\Session_Handler::get_locale()); \phrasea::use_i18n(\Session_Handler::get_locale());
$ld_path = array(dirname(__FILE__) . '/../../../../templates/web'); $ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new Twig_Loader_Filesystem($ld_path); $loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new Twig_Environment($loader); $twig = new \Twig_Environment($loader);
$twig->addExtension(new Twig_Extensions_Extension_I18n()); $twig->addExtension(new \Twig_Extensions_Extension_I18n());
$request = $app['request']; $request = $app['request'];
@@ -125,18 +114,19 @@ class Installer implements ControllerProviderInterface
{ {
$warnings[] = _('It is not recommended to install Phraseanet without HTTPS support'); $warnings[] = _('It is not recommended to install Phraseanet without HTTPS support');
} }
$html = $twig->render( $html = $twig->render(
'/setup/step2.twig' '/setup/step2.twig'
, array( , array(
'locale' => \Session_Handler::get_locale() 'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['available_languages'] , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'available_templates' => \appbox::list_databox_templates() , 'available_templates' => \appbox::list_databox_templates()
, 'version_number' => GV_version , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => GV_version_name , 'version_name' => $app['Core']['Version']->getName()
, 'warnings' => $warnings , 'warnings' => $warnings
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/' , 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
, 'discovered_binaries' => \setup::discover_binaries() , 'discovered_binaries' => \setup::discover_binaries()
, 'rootpath' => dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/' , 'rootpath' => dirname(dirname(dirname(dirname(__DIR__)))) . '/'
) )
); );
@@ -215,7 +205,7 @@ class Installer implements ControllerProviderInterface
if ($databox_name) if ($databox_name)
{ {
$template = new \system_file(dirname(__FILE__) . '/../../../conf.d/data_templates/' . $request->get('db_template') . '.xml'); $template = new \system_file(__DIR__ . '/../../../conf.d/data_templates/' . $request->get('db_template') . '.xml');
$databox = \databox::create($appbox, $connbas, $template, $registry); $databox = \databox::create($appbox, $connbas, $template, $registry);
$user->ACL() $user->ACL()
->give_access_to_sbas(array($databox->get_sbas_id())) ->give_access_to_sbas(array($databox->get_sbas_id()))

View File

@@ -25,7 +25,6 @@ use Silex\ControllerCollection;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Upgrader implements ControllerProviderInterface class Upgrader implements ControllerProviderInterface
{ {
@@ -34,7 +33,6 @@ class Upgrader implements ControllerProviderInterface
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$app['registry'] = new \Setup_Registry(); $app['registry'] = new \Setup_Registry();
$app['available_languages'] = \User_Adapter::detectLanguage($app['registry']);
$app['twig'] = function() $app['twig'] = function()
{ {
return new \supertwig(); return new \supertwig();
@@ -42,7 +40,7 @@ class Upgrader implements ControllerProviderInterface
$controllers->get('/', function() use ($app) $controllers->get('/', function() use ($app)
{ {
require_once dirname(__FILE__) . '/../../../../bootstrap.php'; require_once __DIR__ . '/../../../../bootstrap.php';
$upgrade_status = \Setup_Upgrade::get_status(); $upgrade_status = \Setup_Upgrade::get_status();
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
@@ -51,10 +49,11 @@ class Upgrader implements ControllerProviderInterface
, array( , array(
'locale' => \Session_Handler::get_locale() 'locale' => \Session_Handler::get_locale()
, 'upgrade_status' => $upgrade_status , 'upgrade_status' => $upgrade_status
, 'available_locales' => $app['available_languages'] , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance()) , 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance())
, 'version_number' => GV_version , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => GV_version_name) , 'version_name' => $app['Core']['Version']->getName()
)
); );
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
@@ -63,7 +62,7 @@ class Upgrader implements ControllerProviderInterface
$controllers->get('/status/', function() use ($app) $controllers->get('/status/', function() use ($app)
{ {
require_once dirname(__FILE__) . '/../../../../bootstrap.php'; require_once __DIR__ . '/../../../../bootstrap.php';
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
$datas = \Setup_Upgrade::get_status(); $datas = \Setup_Upgrade::get_status();
@@ -73,7 +72,7 @@ class Upgrader implements ControllerProviderInterface
$controllers->post('/execute/', function() use ($app) $controllers->post('/execute/', function() use ($app)
{ {
require_once dirname(__FILE__) . '/../../../../bootstrap.php'; require_once __DIR__ . '/../../../../bootstrap.php';
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
set_time_limit(0); set_time_limit(0);
session_write_close(); session_write_close();

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea;
use Symfony\Component\HttpFoundation\Request, use Symfony\Component\HttpFoundation\Request,
Symfony\Component\Serializer; Symfony\Component\Serializer;
use Alchemy\Phrasea\Core\Configuration;
require_once __DIR__ . '/../../vendor/Silex/vendor/pimple/lib/Pimple.php'; require_once __DIR__ . '/../../vendor/Silex/vendor/pimple/lib/Pimple.php';
@@ -24,7 +25,22 @@ require_once __DIR__ . '/../../vendor/Silex/vendor/pimple/lib/Pimple.php';
class Core extends \Pimple class Core extends \Pimple
{ {
public function __construct($isDev = false)
protected static $availableLanguages = array(
'ar_SA' => 'العربية'
, 'de_DE' => 'Deutsch'
, 'en_GB' => 'English'
, 'es_ES' => 'Español'
, 'fr_FR' => 'Français'
);
/**
*
* @var Core\Configuration
*/
private $configuration;
public function __construct($environnement)
{ {
/** /**
@@ -32,22 +48,48 @@ class Core extends \Pimple
*/ */
static::initAutoloads(); static::initAutoloads();
/**
* Init conf
*/
$this->init($environnement);
/**
* Set version
*/
$this['Version'] = $this->share(function() $this['Version'] = $this->share(function()
{ {
return new Core\Version(); return new Core\Version();
}); });
$this['EM'] = $this->share(function() /**
* Set Entity Manager using configuration
*/
$configuration = $this->getConfiguration();
$this['EM'] = $this->share(function() use ($configuration)
{ {
$doctrine = new Core\Service\Doctrine(); $doctrine = new Core\Service\Doctrine($configuration->getDoctrine());
return $doctrine->getEntityManager(); return $doctrine->getEntityManager();
}); });
$this['Registry'] = $this->share(function() if (\setup::is_installed())
{ {
return \registry::get_instance(); $this['Registry'] = $this->share(function()
}); {
return \registry::get_instance();
});
\phrasea::start();
$this->enableEvents();
}
else
{
$this['Registry'] = $this->share(function()
{
return new \Setup_Registry();
});
}
/** /**
* Initialize Request * Initialize Request
@@ -72,27 +114,48 @@ class Core extends \Pimple
$this->verifyTimeZone(); $this->verifyTimeZone();
\phrasea::start();
$this->detectLanguage(); $this->detectLanguage();
$this->enableLocales(); $this->enableLocales();
$this->enableEvents();
define('JETON_MAKE_SUBDEF', 0x01); define('JETON_MAKE_SUBDEF', 0x01);
define('JETON_WRITE_META_DOC', 0x02); define('JETON_WRITE_META_DOC', 0x02);
define('JETON_WRITE_META_SUBDEF', 0x04); define('JETON_WRITE_META_SUBDEF', 0x04);
define('JETON_WRITE_META', 0x06); define('JETON_WRITE_META', 0x06);
$gatekeeper = \gatekeeper::getInstance(); if (\setup::is_installed())
$gatekeeper->check_directory(); {
$gatekeeper = \gatekeeper::getInstance();
$gatekeeper->check_directory();
}
return; return;
} }
/** /**
* * Load Configuration
*
* @param type $environnement
*/
private function init($environnement)
{
$this->loadConf($environnement);
if ($this->getConfiguration()->displayErrors())
{
ini_set('display_errors', 1);
error_reporting(E_ALL);
\Symfony\Component\HttpKernel\Debug\ErrorHandler::register();
}
else
{
ini_set('display_errors', 0);
}
}
/**
* Getter
*
* @return Request * @return Request
*/ */
public function getRequest() public function getRequest()
@@ -101,7 +164,8 @@ class Core extends \Pimple
} }
/** /**
* * Getter
*
* @return \Registry * @return \Registry
*/ */
public function getRegistry() public function getRegistry()
@@ -110,7 +174,8 @@ class Core extends \Pimple
} }
/** /**
* * Getter
*
* @return \Doctrine\ORM\EntityManager * @return \Doctrine\ORM\EntityManager
*/ */
public function getEntityManager() public function getEntityManager()
@@ -119,7 +184,8 @@ class Core extends \Pimple
} }
/** /**
* * Getter
*
* @return Alchemy\Phrasea\Core\Version * @return Alchemy\Phrasea\Core\Version
*/ */
public function getVersion() public function getVersion()
@@ -128,7 +194,8 @@ class Core extends \Pimple
} }
/** /**
* * Tell if current seession is authenticated
*
* @return boolean * @return boolean
*/ */
public function isAuthenticated() public function isAuthenticated()
@@ -139,7 +206,8 @@ class Core extends \Pimple
} }
/** /**
* * Return the current authenticated phraseanet user
*
* @return \User_adapter * @return \User_adapter
*/ */
public function getAuthenticatedUser() public function getAuthenticatedUser()
@@ -150,6 +218,19 @@ class Core extends \Pimple
return \User_Adapter::getInstance($session->get_usr_id(), $appbox); return \User_Adapter::getInstance($session->get_usr_id(), $appbox);
} }
/**
* Getter
*
* @return Core\Configuration
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* Set Default application Timezone
*/
protected function verifyTimezone() protected function verifyTimezone()
{ {
if ($this->getRegistry()->is_set('GV_timezone')) if ($this->getRegistry()->is_set('GV_timezone'))
@@ -170,11 +251,17 @@ class Core extends \Pimple
protected function enableEvents() protected function enableEvents()
{ {
\phrasea::load_events(); $events = \eventsmanager_broker::getInstance(\appbox::get_instance(), $this);
$events->start();
return; return;
} }
/**
* Initialiaze phraseanet log process
*
* @return Core
*/
protected function initLoggers() protected function initLoggers()
{ {
$php_log = $this->getRegistry()->get('GV_RootPath') . 'logs/php_error.log'; $php_log = $this->getRegistry()->get('GV_RootPath') . 'logs/php_error.log';
@@ -204,30 +291,43 @@ class Core extends \Pimple
return $this; return $this;
} }
/**
* Return available language for phraseanet
*
* @return Array
*/
public static function getAvailableLanguages()
{
return static::$availableLanguages;
}
/**
* Set Language
*
*/
protected function detectLanguage() protected function detectLanguage()
{ {
$availables = array(
'ar_SA' => 'العربية'
, 'de_DE' => 'Deutsch'
, 'en_GB' => 'English'
, 'es_ES' => 'Español'
, 'fr_FR' => 'Français'
);
$this->getRequest()->setDefaultLocale( $this->getRequest()->setDefaultLocale(
$this->getRegistry()->get('GV_default_lng', 'en_GB') $this->getRegistry()->get('GV_default_lng', 'en_GB')
); );
$cookies = $this->getRequest()->cookies; $cookies = $this->getRequest()->cookies;
if (isset($availables[$cookies->get('locale')])) if (isset(static::$availableLanguages[$cookies->get('locale')]))
{ {
$this->getRequest()->setLocale($cookies->get('locale')); $this->getRequest()->setLocale($cookies->get('locale'));
} }
\Session_Handler::set_locale($this->getRequest()->getLocale());
return; return;
} }
/**
* Finds the path to the file where the class is defined.
*
* @param string $class_name the name of the class we are looking for
*/
protected static function phraseaAutoload($class_name) protected static function phraseaAutoload($class_name)
{ {
if (file_exists(__DIR__ . '/../../../config/classes/' if (file_exists(__DIR__ . '/../../../config/classes/'
@@ -246,6 +346,10 @@ class Core extends \Pimple
return; return;
} }
/**
* Register directory and namespaces for autoloading app classes
*
*/
public static function initAutoloads() public static function initAutoloads()
{ {
require_once __DIR__ . '/../../vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php'; require_once __DIR__ . '/../../vendor/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
@@ -265,6 +369,7 @@ class Core extends \Pimple
'Symfony\\Component\\Yaml' => __DIR__ . '/../../vendor/symfony/src', 'Symfony\\Component\\Yaml' => __DIR__ . '/../../vendor/symfony/src',
'Symfony\\Component\\Console' => __DIR__ . '/../../vendor/symfony/src', 'Symfony\\Component\\Console' => __DIR__ . '/../../vendor/symfony/src',
'Symfony\\Component\\Serializer' => __DIR__ . '/../../vendor/symfony/src', 'Symfony\\Component\\Serializer' => __DIR__ . '/../../vendor/symfony/src',
'Symfony\\Component\\DependencyInjection' => __DIR__ . '/../../vendor/symfony/src',
)); ));
$loader->register(); $loader->register();
@@ -274,6 +379,10 @@ class Core extends \Pimple
return; return;
} }
/**
* Initialize some PHP configuration variables
*
*/
public static function initPHPConf() public static function initPHPConf()
{ {
ini_set('output_buffering', '4096'); ini_set('output_buffering', '4096');
@@ -291,4 +400,29 @@ class Core extends \Pimple
return; return;
} }
/**
* Return the current working environnement (test, dev, prod etc ...)
*
* @return string
*/
public function getEnv()
{
return $this->conf->getEnvironnement();
}
/**
* Load application configuration
*
* @param type $env
*/
private function loadConf($env)
{
$confHandler = new Configuration\Handler(
new Configuration\Application(),
new Configuration\Parser\Yaml()
);
$this->configuration = new Configuration($env, $confHandler);
}
} }

View File

@@ -0,0 +1,208 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Alchemy\Phrasea\Core\Configuration\Application;
use Alchemy\Phrasea\Core\Configuration\Parser as ConfigurationParser;
/**
* Handle configuration file mechanism of phraseanet
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Configuration
{
/**
* The file path of the main configuration file
* @var string
*/
protected $filePathName;
/**
* The environnment name
* @var string
*/
protected $environnement;
/**
* The finale configuration values as an array
* @var ParameterBag\ParameterBag
*/
protected $configuration;
/**
* Class that take care of configuration process
* @var Configuration\Handler
*/
private $configurationHandler;
/**
*
* @param type $envName the name of the loaded environnement
*/
public function __construct($envName, Configuration\Handler $handler)
{
$this->environnement = $envName;
$this->configurationHandler = $handler;
$this->installed = false;
try
{
$handler->getSpecification()->getMainConfigurationFile();
$this->installed = true;
}
catch (\Exception $e)
{
}
}
/**
* Getter
* @return Configuration\Handler
*/
public function getConfigurationHandler()
{
return $this->configurationHandler;
}
/**
* Setter
* @param Configuration\Handler $configurationHandler
*/
public function setConfigurationHandler(Configuration\Handler $configurationHandler)
{
$this->configurationHandler = $configurationHandler;
}
/**
* Return the current used environnement
*
* @return string
*/
public function getEnvironnement()
{
return $this->environnement;
}
/**
* Return the DBAL Doctrine configuration
*
* @return Array
*/
public function getDoctrine()
{
$doctrine = $this->getConfiguration()->get('doctrine', array()); //get doctrine scope
if (count($doctrine) > 0)
{
$doctrine["debug"] = $this->isDebug(); //set debug
if (!!$doctrine["log"]['enable'])
{
$logger = $doctrine["log"]["type"];
if (!in_array($doctrine["log"]["type"], $this->getAvailableDoctrineLogger()))
{
throw new \Exception(sprintf('Unknow logger %s', $logger));
}
$doctrineLogger = $this->getConfiguration()->get($logger); //set logger
$doctrine["logger"] = $doctrineLogger;
}
}
return $doctrine;
}
/**
* Check if current environnement is on debug mode
* Default to false
* @return boolean
*/
public function isDebug()
{
$phraseanet = $this->getPhraseanet();
return isset($phraseanet["debug"]) ? !!$phraseanet["debug"] : false;
}
/**
* Check if current environnement should display errors
* Default to false
* @return boolean
*/
public function displayErrors()
{
$phraseanet = $this->getPhraseanet();
return isset($phraseanet["display_errors"]) ? !!$phraseanet["display_errors"] : false;
}
/**
* Return the phraseanet scope configurations values
*
* @return Array|null
*/
public function getPhraseanet()
{
return $this->getConfiguration()->get('phraseanet', array());
}
/**
* Tell if the application is installed
*
* @return boolean
*/
public function isInstalled()
{
return $this->installed;
}
/**
* Return the configuration
*
* @return ParameterBag\ParameterBag
*/
public function getConfiguration()
{
if (null === $this->configuration)
{
$this->configuration = new Configuration\Parameter();
if($this->installed)
{
$configuration = $this->configurationHandler->handle($this->getEnvironnement());
$this->configuration = new Configuration\Parameter($configuration);
}
}
return $this->configuration;
}
/**
* Return Available logger
*
* @return Array
*/
public function getAvailableDoctrineLogger()
{
return array('echo', 'monolog');
}
}

View File

@@ -0,0 +1,99 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
/**
* Precise some informations about phraseanet configuration mechanism
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Application implements Specification
{
/**
*
* {@inheritdoc}
*/
public function getNonExtendablePath()
{
return array(
array('doctrine', 'dbal')
);
}
/**
*
* {@inheritdoc}
*/
public function getConfFileFromEnvName($name)
{
if ($name === self::EXTENDED_MAIN_KEYWORD)
{
return $this->getMainConfigurationFile();
}
return new \SplFileObject(sprintf("%s/config_%s.%s"
, $this->getConfigurationFilePath()
, $name
, $this->getConfFileExtension())
);
}
/**
*
* {@inheritdoc}
*/
public function getConfigurationFilePath()
{
return __DIR__ . '/../../../../../config';
}
/**
*
* {@inheritdoc}
*/
public function getMainConfigurationFile()
{
$path = __DIR__ . '/../../../../../config/config.yml';
return new \SplFileObject($path);
}
/**
*
* {@inheritdoc}
*/
public function getConfFileExtension()
{
return 'yml';
}
/**
*
* {@inheritdoc}
*/
public function isExtended(Array $env)
{
return isset($env[self::EXTENDED_KEYWORD]);
}
/**
*
* {@inheritdoc}
*/
public function getExtendedEnvName(Array $env)
{
return $this->isExtended($env) ? $env[self::EXTENDED_KEYWORD] : null;
}
}

View File

@@ -0,0 +1,231 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
use \Symfony\Component\Yaml\Yaml;
/**
* Handle configuration mechanism
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Handler
{
/**
* Configuration file specification interface
* @var ConfigurationSpecification
*/
protected $confSpecification;
/**
* A file parser interface
* @var Parser\ParserInterface
*/
protected $parser;
/**
* Tell handler the configuration specification ans which parser to use
*
* @param ConfigurationSpecification $configSpec
* @param Parser\ParserInterface $parser
*/
public function __construct(Specification $configSpec, Parser $parser)
{
$this->confSpecification = $configSpec;
$this->parser = $parser;
}
/**
* Getter
* @return Specification
*/
public function getSpecification()
{
return $this->confSpecification;
}
/**
* Getter
* @return Parser
*/
public function getParser()
{
return $this->parser;
}
/**
* Stacks all envrironnement in $env that extends the loaded configuration file
*
* @param SplFileObject $file File of the current loaded config file
* @param array $envs A stack of conf environnments
* @return array
*/
public function retrieveExtendedEnvFromFile(\SplFileObject $file, Array $allEnvs = array())
{
$env = $this->parser->parse($file);
//stack current env to allEnvs
$allEnvs[] = $env;
//check if the loaded environnement extends another configuration file
if ($this->confSpecification->isExtended($env))
{
try
{
//get extended environnement name
$envName = $this->confSpecification->getExtendedEnvName($env);
//get extended configuration file
$file = $this->confSpecification->getConfFileFromEnvName($envName);
//recurse
return $this->retrieveExtendedEnvFromFile($file, $allEnvs);
}
catch (\Exception $e)
{
throw new \Exception(sprintf("filename %s not found", $file->getPathname()));
}
}
else
{
return $allEnvs;
}
}
/**
* Get the value of a specified data path
*
* @param array $data The array where the data are stored
* @param array $path The Path as an array example : array('path', 'to', 'my', 'value')
* @return mixed
*/
private function getDataPath(Array $data, Array $path)
{
$found = true;
for ($x = 0; ($x < count($path) && $found); $x++)
{
$key = $path[$x];
if (isset($data[$key]))
{
$data = $data[$key];
}
else
{
$found = false;
}
}
return $found ? $data : null;
}
/**
* Handle the configuration process and return the final configuration
*
* @param strinig $name the name of the loaded environnement
* @return Array
*/
public function handle($name)
{
//get the corresepondant file
$file = $this->confSpecification->getConfFileFromEnvName($name);
//get all extended configuration from current env
$allEnvs = $this->retrieveExtendedEnvFromFile($file);
//Last env is the main one
$mainEnv = array_pop($allEnvs);
$excludedPath = $pathToprocess = $this->confSpecification->getNonExtendablePath();
//at least 2 envs and one path to process
if (count($allEnvs) >= 1 && count($excludedPath) >= 1)
{
foreach ($allEnvs as $currentEnv) // run trought environnements
{
foreach ($pathToprocess as $kpath => $processedPath) //run throught path
{
$valueToReplace = $this->getDataPath($currentEnv, $processedPath); //retrive the value to replace
if (null !== $valueToReplace)
{
// reset current path
$currentPath = array();
//callback to iterate over the main conf environnement and replace value from extended file
$map = function($item, $key) use (&$mainEnv, $valueToReplace, &$map, &$currentPath, $processedPath)
{
if (count(array_diff($processedPath, $currentPath)) === 0) // current path and processed path match
{
/**
* Replace current value of the $currentpath in $searchArray by $value
*/
$replace = function(&$searchArray, $currentPath, $value) use (&$replace)
{
foreach ($searchArray as $k => $v)
{
if ($k === $currentPath[0]) //if key of searched path equal key of search array
{
array_shift($currentPath); //reduce path
if (is_array($v) && count($currentPath) !== 0) //continue to run trought search array
{
$replace(&$searchArray[$k], $currentPath, $value);
}
elseif (count($currentPath) === 0) //no more scope to looking for
{
$searchArray[$k] = $value;
break; //quit
}
}
}
};
$replace($mainEnv, $currentPath, $valueToReplace);
}
elseif (is_array($item)) // if current item is an array
{
$currentPath[] = $key; // add item's key to current path
array_walk($item, $map); // and dig into the current item
}
else //wrong path
{
$currentPath = array(); //reset
}
};
//run trough the main conf environnement
array_walk($mainEnv, $map);
//once done
//reduce the paths to process
unset($pathToprocess[$kpath]);
break;
}
}
}
}
//replace all other value
if(count($allEnvs) >= 1)
{
foreach($allEnvs as $extendedEnv)
$mainEnv = array_replace_recursive($mainEnv, $extendedEnv);
}
return $mainEnv;
}
}

View File

@@ -0,0 +1,37 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
/**
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Parameter extends ParameterBag
{
public function get($name, $default = null)
{
try
{
return parent::get($name);
}
catch(ParameterNotFoundException $e)
{
return $default;
}
}
}

View File

@@ -9,13 +9,22 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Alchemy\Phrasea\Core\Configuration;
/** /**
* * A interface to parse configuration file
* @package Exception *
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Exception_Basket_NotFound extends Exception_NotFound interface Parser
{ {
/**
} * Parse the configuration file $file to an array
*
* @param \SplFileObject $file the file to parse
* @return Array
*/
public function parse(\SplFileObject $file);
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration\Parser;
use Symfony\Component\Yaml\Yaml as SfYaml;
/**
* Parse a configuration file in yaml format and return an array of values
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Yaml implements \Alchemy\Phrasea\Core\Configuration\Parser
{
/**
*
* @Override
*/
public function parse(\SplFileObject $file)
{
try
{
return SfYaml::parse($file->getPathname());
}
catch(\Exception $e)
{
throw new \Exception(sprintf('Failed to parse the configuration file %s', $e->getMessage()));
}
}
}

View File

@@ -0,0 +1,90 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
/**
* A interface to precise some specific configuration file mechanism
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
interface Specification
{
/**
* Keywords to detect extended file
*/
const EXTENDED_KEYWORD = 'extends';
/**
* Keywords to detect main file
*/
const EXTENDED_MAIN_KEYWORD = 'main';
/**
* Return the main configuration file
*
* @return \SplFileObject
*/
public function getMainConfigurationFile();
/**
* Return an array of paths that CAN'T be extended by ONLY one or more of their value
* but must be fully replaced with new values
*
* example:
* array(array('PATH', 'TO', 'MY', 'SCOPE1', array('SCOPE2')
*
* So $extendedConf['PATH']['TO']['MY']['SCOPE'] will fully replace
* $mainConf['PATH']['TO']['MY']['SCOPE'];
*
* @return Array
*/
public function getNonExtendablePath();
/**
* Return the configuration file from an environnment name
*
* @return \SplFileObject
*/
public function getConfFileFromEnvName($name);
/**
* Return the path to the configuration file
*
* @return string
*/
public function getConfigurationFilePath();
/**
* Return the configurationFile extension
*
* @return string
*/
public function getConfFileExtension();
/**
* Check wether the environnement $env extends another one
*
* @param type $env
* @return boolean
*/
public function isExtended(Array $env);
/**
* Return the extends environnement name null if extends nothing
*
* @param Array an environnement
* @return mixed|null
*/
public function getExtendedEnvName(Array $env);
}

View File

@@ -9,10 +9,10 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Alchemy\Phrasea\Core\Service; namespace Alchemy\Phrasea\Core\Service;
use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Types\Type;
use Doctrine\Common\Cache\AbstractCache;
/** /**
* *
@@ -22,19 +22,44 @@ use Doctrine\DBAL\Types\Type;
*/ */
class Doctrine class Doctrine
{ {
const MEMCACHED = 'memcached';
const ARRAYCACHE = 'array';
const APC = 'apc';
protected $entityManager; protected $entityManager;
public function __construct() public function __construct(Array $doctrineConfiguration = array())
{ {
require_once __DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor/doctrine-common/lib/Doctrine/Common/ClassLoader.php'; require_once __DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor/doctrine-common/lib/Doctrine/Common/ClassLoader.php';
static::loadClasses(); static::loadClasses();
$config = new \Doctrine\ORM\Configuration(); $config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache); //debug mode
$debug = isset($doctrineConfiguration["debug"]) ? : false;
//doctrine cache
$cache = isset($doctrineConfiguration["orm"]["cache"]) ? $doctrineConfiguration["orm"]["cache"] : false;
//doctrine log configuration
$log = isset($doctrineConfiguration["log"]) ? $doctrineConfiguration["log"] : false;
//service logger configuration
$logger = !isset($doctrineConfiguration['logger']) ? : $doctrineConfiguration['logger'];
//default query cache & meta chache
$metaCache = $this->getCache();
$queryCache = $this->getCache();
//handle cache
$this->handleCache($metaCache, $queryCache, $cache, $debug);
//Handle logs
$this->handleLogs($config, $log, $logger);
//set caches
$config->setMetadataCacheImpl($metaCache);
$config->setQueryCacheImpl($queryCache);
//define autoregeneration of proxies base on debug mode
$config->setAutoGenerateProxyClasses($debug);
$chainDriverImpl = new \Doctrine\ORM\Mapping\Driver\DriverChain(); $chainDriverImpl = new \Doctrine\ORM\Mapping\Driver\DriverChain();
@@ -52,24 +77,31 @@ class Doctrine
$config->setProxyNamespace('Proxies'); $config->setProxyNamespace('Proxies');
require __DIR__ . '/../../../../../config/connexion.inc'; $dbalConf = isset($doctrineConfiguration["dbal"]) ? $doctrineConfiguration["dbal"] : false;
if (!$dbalConf)
{
// throw new Exception("Unable to read dbal configuration");
require __DIR__ . '/../../../../../config/connexion.inc';
$dbalConf = array(
'dbname' => $dbname,
'user' => $user,
'password' => $password,
'host' => $hostname,
'driver' => 'pdo_mysql',
);
}
$connectionOptions = array(
'dbname' => $dbname,
'user' => $user,
'password' => $password,
'host' => $hostname,
'driver' => 'pdo_mysql',
);
$evm = new \Doctrine\Common\EventManager(); $evm = new \Doctrine\Common\EventManager();
$evm->addEventSubscriber(new \Gedmo\Timestampable\TimestampableListener()); $evm->addEventSubscriber(new \Gedmo\Timestampable\TimestampableListener());
$this->entityManager = \Doctrine\ORM\EntityManager::create($connectionOptions, $config, $evm); $this->entityManager = \Doctrine\ORM\EntityManager::create($dbalConf, $config, $evm);
$this->addTypes(); $this->addTypes();
return $this; return $this;
} }
@@ -77,7 +109,7 @@ class Doctrine
{ {
return $this->entityManager; return $this->entityManager;
} }
public function getVersion() public function getVersion()
{ {
return \Doctrine\Common\Version::VERSION; return \Doctrine\Common\Version::VERSION;
@@ -98,6 +130,18 @@ class Doctrine
); );
$classLoader->register(); $classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'Doctrine\Common\DataFixtures'
, realpath(__DIR__ . '/../../../../vendor/data-fixtures/lib')
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'PhraseaFixture'
, realpath(__DIR__ . '/../../../../conf.d/')
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader( $classLoader = new \Doctrine\Common\ClassLoader(
'Doctrine\Common' 'Doctrine\Common'
, realpath(__DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor/doctrine-common/lib') , realpath(__DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor/doctrine-common/lib')
@@ -121,19 +165,33 @@ class Doctrine
, realpath(__DIR__ . '/../../../../Doctrine') , realpath(__DIR__ . '/../../../../Doctrine')
); );
$classLoader->register(); $classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader( $classLoader = new \Doctrine\Common\ClassLoader(
'Symfony' 'Symfony'
, realpath(__DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor') , realpath(__DIR__ . '/../../../../vendor/doctrine2-orm/lib/vendor')
); );
$classLoader->register(); $classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'Doctrine\Logger'
, realpath(__DIR__ . '/../../../../')
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader(
'Monolog'
, realpath(__DIR__ . '/../../../../vendor/Silex/vendor/monolog/src')
);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader( $classLoader = new \Doctrine\Common\ClassLoader(
'Types' 'Types'
, realpath(__DIR__ . '/../../../../Doctrine') , realpath(__DIR__ . '/../../../../Doctrine')
); );
$classLoader->register(); $classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader( $classLoader = new \Doctrine\Common\ClassLoader(
@@ -145,23 +203,167 @@ class Doctrine
return; return;
} }
protected function addTypes() protected function addTypes()
{ {
$platform = $this->entityManager->getConnection()->getDatabasePlatform(); $platform = $this->entityManager->getConnection()->getDatabasePlatform();
Type::addType('blob', 'Types\Blob'); if(!Type::hasType('blob'))
Type::addType('enum', 'Types\Enum'); Type::addType('blob', 'Types\Blob');
Type::addType('longblob', 'Types\LongBlob'); if(!Type::hasType('enum'))
Type::addType('varbinary', 'Types\VarBinary'); Type::addType('enum', 'Types\Enum');
if(!Type::hasType('longblob'))
Type::addType('longblob', 'Types\LongBlob');
if(!Type::hasType('varbinary'))
Type::addType('varbinary', 'Types\VarBinary');
$platform->registerDoctrineTypeMapping('enum', 'enum'); $platform->registerDoctrineTypeMapping('enum', 'enum');
$platform->registerDoctrineTypeMapping('blob', 'blob'); $platform->registerDoctrineTypeMapping('blob', 'blob');
$platform->registerDoctrineTypeMapping('longblob', 'longblob'); $platform->registerDoctrineTypeMapping('longblob', 'longblob');
$platform->registerDoctrineTypeMapping('varbinary', 'varbinary'); $platform->registerDoctrineTypeMapping('varbinary', 'varbinary');
return; return;
} }
/**
* Return a cache object according to the $name
*
* @param type $cacheName
*/
private function getCache($cacheName = self::ARRAYCACHE)
{
switch ($cacheName)
{
case self::MEMCACHED:
$cache = new \Doctrine\Common\Cache\MemcacheCache();
break;
case self::APC:
$cache = new \Doctrine\Common\Cache\ApcCache();
break;
case self::ARRAYCACHE:
default:
$cache = new \Doctrine\Common\Cache\ArrayCache();
break;
}
return $cache;
}
/**
* Handle Cache configuration
*
* @param AbstractCache $metaCache
* @param AbstractCache $queryCache
* @param type $cache
* @param type $debug
*/
private function handleCache(AbstractCache &$metaCache, AbstractCache &$queryCache, $cache, $debug)
{
if ($cache && !$debug)
{
//define query cache
$cacheName = isset($cache["query"]) ? $cache["query"] : self::ARRAYCACHE;
$queryCache = $this->getCache($cacheName);
//define metadatas cache
$cacheName = isset($cache["metadata"]) ? $cache["metadata"] : self::ARRAYCACHE;
$metaCache = $this->getCache($cacheName);
}
}
/**
* Handle logs configuration
*
* @param \Doctrine\ORM\Configuration $config
* @param type $log
* @param type $logger
*/
private function handleLogs(\Doctrine\ORM\Configuration &$config, $log, $logger)
{
$logEnable = isset($log["enable"]) ? !!$log["enable"] : false;
if ($logEnable)
{
$loggerService = isset($log["type"]) ? $log["type"] : '';
switch ($loggerService)
{
case 'monolog':
//defaut to main handler
$doctrineHandler = isset($log["handler"]) ? $log["handler"] : 'main';
if (!isset($logger["handlers"]))
{
throw new \Exception("You must specify at least on monolog handler");
}
if (!array_key_exists($doctrineHandler, $logger["handlers"]))
{
throw new \Exception(sprintf('Unknow monolog handler %s'), $handlerType);
}
$handlerName = ucfirst($logger["handlers"][$doctrineHandler]["type"]);
$handlerClassName = sprintf('\Monolog\Handler\%sHandler', $handlerName);
if (!class_exists($handlerClassName))
{
throw new \Exception(sprintf('Unknow monolog handler class %s', $handlerClassName));
}
if (!isset($log["filename"]))
{
throw new \Exception('you must specify a file to write "filename: my_filename"');
}
$logPath = __DIR__ . '/../../../../../logs';
$file = sprintf('%s/%s', $logPath, $log["filename"]);
if ($doctrineHandler == 'rotate')
{
$maxDay = isset($log["max_day"]) ? (int) $log["max_day"] : (int) $logger["max_day"];
$handlerInstance = new $handlerClassName($file, $maxDay);
}
else
{
$handlerInstance = new $handlerClassName($file);
}
$monologLogger = new \Monolog\Logger('query-logger');
$monologLogger->pushHandler($handlerInstance);
if (isset($log["output"]))
{
$output = $log["output"];
}
elseif (isset($logger["output"]))
{
$output = $logger["output"];
}
else
{
$output = null;
}
if (null === $output)
{
$sqlLogger = new \Doctrine\Logger\MonologSQLLogger($monologLogger);
}
else
{
$sqlLogger = new \Doctrine\Logger\MonologSQLLogger($monologLogger, $output);
}
$config->setSQLLogger($sqlLogger);
break;
case 'echo':
default:
$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
break;
}
}
}
} }

View File

@@ -22,7 +22,11 @@ use Alchemy\Phrasea\Core;
class Helper class Helper
{ {
private $core; /**
*
* @var Alchemy\Phrasea\Core\Kernel
*/
protected $core;
/** /**
* *

View File

@@ -12,7 +12,7 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\RecordsAbstract as RecordHelper; use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;
/** /**
* *

View File

@@ -8,13 +8,17 @@
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper,
use Alchemy\Phrasea\Helper\RecordsAbstract as RecordHelper; Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Edit Record Helper
* This object handles /edit/ request and filters records that user can edit
*
* It prepares metadatas, databases structures.
* *
* @package * @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
@@ -64,16 +68,21 @@ class Edit extends RecordHelper
* @var boolean * @var boolean
*/ */
protected $works_on_unique_sbas = true; protected $works_on_unique_sbas = true;
/**
*
* @var type
*/
protected $has_thesaurus = false; protected $has_thesaurus = false;
/**
*
public function __construct(Request $request) * @param \Alchemy\Phrasea\Core $core
* @return Edit
*/
public function __construct(\Alchemy\Phrasea\Core $core)
{ {
$appbox = \appbox::get_instance(); parent::__construct($core);
parent::__construct($request);
if ($this->is_single_grouping()) if ($this->is_single_grouping())
{ {
@@ -186,9 +195,7 @@ class Edit extends RecordHelper
protected function generate_javascript_elements() protected function generate_javascript_elements()
{ {
$_lst = array(); $_lst = array();
$appbox = \appbox::get_instance(); $user = $this->getCore()->getAuthenticatedUser();
$session = $appbox->get_session();
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$twig = new \supertwig(); $twig = new \supertwig();
foreach ($this->selection as $record) foreach ($this->selection as $record)
@@ -251,7 +258,7 @@ class Edit extends RecordHelper
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
$_lst[$indice]['type'] = $record->get_type(); $_lst[$indice]['type'] = $record->get_type();
} }
@@ -282,7 +289,7 @@ class Edit extends RecordHelper
$T_sgval['b' . $base_id] = array(); $T_sgval['b' . $base_id] = array();
$collection = \collection::get_from_base_id($base_id); $collection = \collection::get_from_base_id($base_id);
if ($sxe = simplexml_load_string($collection->get_prefs())) if ($sxe = simplexml_load_string($collection->get_prefs()))
{ {
$z = $sxe->xpath('/baseprefs/sugestedValues'); $z = $sxe->xpath('/baseprefs/sugestedValues');
@@ -292,7 +299,7 @@ class Edit extends RecordHelper
foreach ($z[0] as $ki => $vi) // les champs foreach ($z[0] as $ki => $vi) // les champs
{ {
$field = $databox->get_meta_structure()->get_element_by_name($ki); $field = $databox->get_meta_structure()->get_element_by_name($ki);
if (!$field) if (!$field)
continue; // champ inconnu dans la structure ? continue; // champ inconnu dans la structure ?
@@ -323,9 +330,7 @@ class Edit extends RecordHelper
protected function generate_javascript_status() protected function generate_javascript_status()
{ {
$_tstatbits = array(); $_tstatbits = array();
$appbox = \appbox::get_instance(); $user = $this->getCore()->getAuthenticatedUser();
$session = $appbox->get_session();
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
if ($user->ACL()->has_right('changestatus')) if ($user->ACL()->has_right('changestatus'))
{ {
@@ -441,7 +446,7 @@ class Edit extends RecordHelper
try try
{ {
$reg_record = $this->get_grouping_head(); $reg_record = $this->get_grouping_head();
$reg_sbas_id = $reg_record->get_base_id(); $reg_sbas_id = $reg_record->get_sbas_id();
$newsubdef_reg = new record_adapter($reg_sbas_id, $request->get('newrepresent')); $newsubdef_reg = new record_adapter($reg_sbas_id, $request->get('newrepresent'));
@@ -457,12 +462,11 @@ class Edit extends RecordHelper
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
} }
if (!is_array($request->get('mds'))) if (!is_array($request->get('mds')))
return $this; return $this;
$sbas_id = (int) $request->get('sbid'); $sbas_id = (int) $request->get('sbid');

View File

@@ -12,7 +12,7 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\RecordsAbstract as RecordHelper; use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
/** /**
@@ -43,15 +43,13 @@ class Feed extends RecordHelper
/** /**
* *
* @param Request $request * @param \Alchemy\Phrasea\Core $core
* @return RecordsFeed * @return Feed
*/ */
public function __construct(Request $request) public function __construct(\Alchemy\Phrasea\Core $core)
{ {
$appbox = \appbox::get_instance(); parent::__construct($core);
parent::__construct($request);
if ($this->is_single_grouping()) if ($this->is_single_grouping())
{ {
$record = array_pop($this->selection->get_elements()); $record = array_pop($this->selection->get_elements());

View File

@@ -9,7 +9,7 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Alchemy\Phrasea\Helper; namespace Alchemy\Phrasea\Helper\Record;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -20,7 +20,7 @@ use Symfony\Component\HttpFoundation\Request;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class RecordsAbstract class Helper extends \Alchemy\Phrasea\Helper\Helper
{ {
/** /**
@@ -92,45 +92,38 @@ class RecordsAbstract
/** /**
* *
* @var basket_adapter * @var \Entities\Basket
*/ */
protected $original_basket; protected $original_basket;
/** /**
* *
* @return action_move * @param \Alchemy\Phrasea\Core $core
* @return Helper
*/ */
public function __construct(Request $request) public function __construct(\Alchemy\Phrasea\Core $core)
{ {
$this->request = $request; parent::__construct($core);
$this->selection = new \set_selection(); $this->selection = new \set_selection();
$request = $core->getRequest();
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$usr_id = $appbox->get_session()->get_usr_id(); $usr_id = $appbox->get_session()->get_usr_id();
if (trim($request->get('ssel')) !== '') if (trim($request->get('ssel')) !== '')
{ {
$basket = \basket_adapter::getInstance($appbox, $request->get('ssel'), $usr_id); $em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
if ($basket->is_grouping() && $this->flatten_groupings === true)
{ /* @var $$repository \Repositories\BasketRepository */
foreach ($basket->get_elements() as $basket_element) $Basket = $repository->findUserBasket($request->get('ssel'), $this->getCore()->getAuthenticatedUser());
{
/* @var $basket_element basket_element_adapter */ $this->selection->load_basket($Basket);
$this->selection->add_element($basket_element->get_record());
} $this->is_basket = true;
} $this->original_basket = $Basket;
elseif($basket->is_grouping())
{
$grouping = new record_adapter($basket->get_sbas_id(), $basket->get_record_id());
$this->selection->add_element($grouping);
}
else
{
$this->selection->load_basket($basket);
$this->is_basket = true;
}
$this->original_basket = $basket;
} }
else else
{ {
@@ -159,7 +152,7 @@ class RecordsAbstract
/** /**
* If the original selection was a basket, returns the basket object * If the original selection was a basket, returns the basket object
* *
* @return basket_adapter * @return \Entities\Basket
*/ */
public function get_original_basket() public function get_original_basket()
{ {
@@ -304,17 +297,7 @@ class RecordsAbstract
return $this->selection->serialize_list(); return $this->selection->serialize_list();
} }
public function get_request() public function grep_records(\Closure $closure)
{
return $this->request;
}
public function set_request($request)
{
$this->request = $request;
}
public function grep_records(Closure $closure)
{ {
foreach ($this->selection->get_elements() as $record) foreach ($this->selection->get_elements() as $record)
{ {

View File

@@ -11,8 +11,7 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;
use Alchemy\Phrasea\Helper\RecordsAbstract as RecordHelper;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
/** /**
@@ -23,33 +22,37 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class MoveCollection extends RecordHelper class MoveCollection extends RecordHelper
{ {
/** /**
* *
* @var Array * @var Array
*/ */
protected $required_rights = array('candeleterecord'); protected $required_rights = array('candeleterecord');
/** /**
* *
* @var Array * @var Array
*/ */
protected $available_destinations; protected $available_destinations;
/** /**
* *
*/ */
protected $works_on_unique_sbas = true; protected $works_on_unique_sbas = true;
/** /**
* Constructor
* *
* @return action_move * @param \Alchemy\Phrasea\Core $core
* @return MoveCollection
*/ */
public function __construct(Request $request) public function __construct(\Alchemy\Phrasea\Core $core)
{ {
parent::__construct($request); parent::__construct($core);
$this->evaluate_destinations(); $this->evaluate_destinations();
return $this; return $this;
} }
/** /**
* Check which collections can receive the documents * Check which collections can receive the documents
* *
@@ -60,14 +63,13 @@ class MoveCollection extends RecordHelper
$this->available_destinations = array(); $this->available_destinations = array();
if (!$this->is_possible) if (!$this->is_possible)
return $this; return $this;
$appbox = \appbox::get_instance(); $this->available_destinations = array_keys(
$session = $appbox->get_session(); $this->getCore()->getAuthenticatedUser()->ACL()->get_granted_base(
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox); array('canaddrecord'), array($this->sbas_id)
)
$this->available_destinations = array_keys($user->ACL()->get_granted_base(array('canaddrecord'), array($this->sbas_id))); );
return $this; return $this;
} }
@@ -95,8 +97,7 @@ class MoveCollection extends RecordHelper
public function execute(Request $request) public function execute(Request $request)
{ {
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$session = $appbox->get_session(); $user = $this->getCore()->getAuthenticatedUser();
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$base_dest = $base_dest =
$user->ACL()->has_right_on_base($request->get('base_id'), 'canaddrecord') ? $user->ACL()->has_right_on_base($request->get('base_id'), 'canaddrecord') ?
@@ -130,4 +131,5 @@ class MoveCollection extends RecordHelper
return $this; return $this;
} }
} }

View File

@@ -0,0 +1,94 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper,
Symfony\Component\HttpFoundation\Request;
/**
* Edit Record Helper
* This object handles /edit/ request and filters records that user can edit
*
* It prepares metadatas, databases structures.
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Printer extends RecordHelper
{
protected $flatten_groupings = true;
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Printer
*/
public function __construct(\Alchemy\Phrasea\Core $core)
{
parent::__construct($core);
$grep = function(\record_adapter $record){
try
{
return $record->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE ||
$record->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
}
catch(\Exception $e)
{
return false;
}
};
$this->grep_records($grep);
}
public function get_count_preview()
{
$n = 0;
foreach($this->get_elements() as $element)
{
try
{
$element->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
$n++;
}
catch(\Exception $e)
{
}
}
return $n;
}
public function get_count_thumbnail()
{
$n = 0;
foreach($this->get_elements() as $element)
{
try
{
$element->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE;
$n++;
}
catch(\Exception $e)
{
}
}
return $n;
}
}

View File

@@ -12,7 +12,7 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Helper\RecordsAbstract as RecordHelper; use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;
/** /**
* *

View File

@@ -19,11 +19,9 @@ use Symfony\Component\HttpFoundation\Request;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Edit class Edit extends \Alchemy\Phrasea\Helper\Helper
{ {
protected $request;
/** /**
* *
* @var array * @var array
@@ -42,19 +40,11 @@ class Edit
*/ */
protected $base_id; protected $base_id;
/** public function __construct(\Alchemy\Phrasea\Core $core)
*
* @param Symfony\Component\HttpFoundation\Request $request
* @return module_admin_route_users_edit
*/
public function __construct(Request $request)
{ {
parent::__construct($core);
$this->users = explode(';', $request->get('users')); $this->users = explode(';', $request->get('users'));
$this->request = $request;
$appbox = \appbox::get_instance();
$session = $appbox->get_session();
$users = array(); $users = array();
foreach ($this->users as $usr_id) foreach ($this->users as $usr_id)
{ {
@@ -83,23 +73,26 @@ class Edit
protected function delete_user(\User_Adapter $user) protected function delete_user(\User_Adapter $user)
{ {
$appbox = \appbox::get_instance(); $master = $this->getCore()->getAuthenticatedUser();
$session = $appbox->get_session();
$list = array_keys(\User_Adapter::getInstance($session->get_usr_id(), $appbox)->ACL()->get_granted_base(array('canadmin'))); $list = array_keys($master->ACL()->get_granted_base(array('canadmin')));
$user->ACL()->revoke_access_from_bases($list); $user->ACL()->revoke_access_from_bases($list);
if ($user->ACL()->is_phantom()) if ($user->ACL()->is_phantom())
{
$user->delete(); $user->delete();
}
return $this; return $this;
} }
public function get_users_rights() public function get_users_rights()
{ {
$user = $this->getCore()->getAuthenticatedUser();
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$session = $appbox->get_session();
$list = array_keys(\User_Adapter::getInstance($session->get_usr_id(), $appbox)->ACL()->get_granted_base(array('canadmin'))); $list = array_keys($user->ACL()->get_granted_base(array('canadmin')));
$sql = "SELECT $sql = "SELECT
b.sbas_id, b.sbas_id,
@@ -203,7 +196,7 @@ class Edit
public function get_quotas() public function get_quotas()
{ {
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->getCore()->getRequest()->get('base_id');
// $this->base_id = (int) $parm['base_id']; // $this->base_id = (int) $parm['base_id'];
@@ -230,7 +223,7 @@ class Edit
public function get_masks() public function get_masks()
{ {
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->getCore()->getRequest()->get('base_id');
$sql = "SELECT BIN(mask_and) AS mask_and, BIN(mask_xor) AS mask_xor $sql = "SELECT BIN(mask_and) AS mask_and, BIN(mask_xor) AS mask_xor
FROM basusr FROM basusr
@@ -334,7 +327,7 @@ class Edit
public function get_time() public function get_time()
{ {
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->getCore()->getRequest()->get('base_id');
$sql = "SELECT u.usr_id, time_limited, limited_from, limited_to $sql = "SELECT u.usr_id, time_limited, limited_from, limited_to
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id) FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
@@ -540,7 +533,14 @@ class Edit
return $this; return $this;
} }
$appbox = \appbox::get_instance(); $user = User_adapter::getInstance(array_pop($this->users), appbox::get_instance());
if ($user->is_template())
{
return $this;
}
$appbox = appbox::get_instance();
$session = $appbox->get_session(); $session = $appbox->get_session();
$request = \http_request::getInstance(); $request = \http_request::getInstance();
@@ -584,15 +584,45 @@ class Edit
return $this; return $this;
} }
public function apply_template()
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$template = \User_adapter::getInstance($this->request->get('template'), $appbox);
if ($template->get_template_owner()->get_id() != $session->get_usr_id())
{
throw new \Exception_Forbidden('You are not the owner of the template');
}
$current_user = \User_adapter::getInstance($session->get_usr_id(), $appbox);
$base_ids = array_keys($current_user->ACL()->get_granted_base(array('canadmin')));
foreach ($this->users as $usr_id)
{
$user = \User_adapter::getInstance($usr_id, $appbox);
if($user->is_template())
{
continue;
}
$user->ACL()->apply_model($template, $base_ids);
}
return $this;
}
public function apply_quotas() public function apply_quotas()
{ {
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->getCore()->getRequest()->get('base_id');
foreach ($this->users as $usr_id) foreach ($this->users as $usr_id)
{ {
$user = \User_Adapter::getInstance($usr_id, \appbox::get_instance()); $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance());
if ($this->request->get('quota')) if ($this->getCore()->getRequest()->get('quota'))
$user->ACL()->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes')); $user->ACL()->set_quotas_on_base($this->base_id, $this->getCore()->getRequest()->get('droits'), $this->getCore()->getRequest()->get('restes'));
else else
$user->ACL()->remove_quotas_on_base($this->base_id); $user->ACL()->remove_quotas_on_base($this->base_id);
} }
@@ -602,12 +632,13 @@ class Edit
public function apply_masks() public function apply_masks()
{ {
$this->base_id = (int) $this->request->get('base_id'); $request = $this->getCore()->getRequest();
$this->base_id = (int) $request->get('base_id');
$vand_and = $this->request->get('vand_and'); $vand_and = $request->get('vand_and');
$vand_or = $this->request->get('vand_or'); $vand_or = $request->get('vand_or');
$vxor_and = $this->request->get('vxor_and'); $vxor_and = $request->get('vxor_and');
$vxor_or = $this->request->get('vxor_or'); $vxor_or = $request->get('vxor_or');
if ($vand_and && $vand_or && $vxor_and && $vxor_or) if ($vand_and && $vand_or && $vxor_and && $vxor_or)
{ {
@@ -624,13 +655,14 @@ class Edit
public function apply_time() public function apply_time()
{ {
$request = $this->getCore()->getRequest();
$this->base_id = (int) $request->get('base_id');
$this->base_id = (int) $this->request->get('base_id'); $dmin = $request->get('dmin') ? new \DateTime($request->get('dmin')) : null;
$dmax = $request->get('dmax') ? new \DateTime($request->get('dmax')) : null;
$dmin = $this->request->get('dmin') ? new \DateTime($this->request->get('dmin')) : null; $activate = $request->get('limit');
$dmax = $this->request->get('dmax') ? new \DateTime($this->request->get('dmax')) : null;
$activate = $this->request->get('limit');
foreach ($this->users as $usr_id) foreach ($this->users as $usr_id)
{ {

View File

@@ -19,10 +19,9 @@ use Symfony\Component\HttpFoundation\Request;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Manage class Manage extends \Alchemy\Phrasea\Helper\Helper
{ {
protected $request;
/** /**
* *
* @var array * @var array
@@ -39,18 +38,11 @@ class Manage
*/ */
protected $usr_id; protected $usr_id;
public function __construct(Request $request) public function search()
{
$this->request = $request;
return $this;
}
public function search(Request $request)
{ {
$request = $this->getCore()->getRequest();
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$session = $appbox->get_session();
$offset_start = (int) $request->get('offset_start'); $offset_start = (int) $request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start; $offset_start = $offset_start < 0 ? 0 : $offset_start;
@@ -69,7 +61,7 @@ class Manage
, 'offset_start' => $offset_start , 'offset_start' => $offset_start
); );
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox); $user = $this->getCore()->getAuthenticatedUser();
$query = new \User_Query($appbox); $query = new \User_Query($appbox);
if (is_array($request->get('base_id'))) if (is_array($request->get('base_id')))
@@ -110,18 +102,25 @@ class Manage
if (is_null($v)) if (is_null($v))
$this->query_parms[$k] = false; $this->query_parms[$k] = false;
} }
$query = new User_Query($appbox);
$templates = $query
->only_templates(true)
->execute()->get_results();
return array( return array(
'users' => $this->results, 'users' => $this->results,
'parm' => $this->query_parms, 'parm' => $this->query_parms,
'invite_user' => $invite, 'invite_user' => $invite,
'autoregister_user' => $autoregister 'autoregister_user' => $autoregister,
'templates' => $templates
); );
} }
public function create_newuser() public function create_newuser()
{ {
$email = $this->request->get('value'); $email = $this->getCore()->getRequest()->get('value');
if(!\mail::validateEmail($email)) if(!\mail::validateEmail($email))
{ {
@@ -153,7 +152,7 @@ class Manage
public function create_template() public function create_template()
{ {
$name = $this->request->get('value'); $name = $this->getCore()->getRequest()->get('value');
if(trim($name) === '') if(trim($name) === '')
{ {
@@ -161,7 +160,7 @@ class Manage
} }
$appbox = \appbox::get_instance(); $appbox = \appbox::get_instance();
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = $this->getCore()->getAuthenticatedUser();
$created_user = \User_Adapter::create($appbox, $name, \random::generatePassword(16), null, false, false); $created_user = \User_Adapter::create($appbox, $name, \random::generatePassword(16), null, false, false);
$created_user->set_template($user); $created_user->set_template($user);

View File

@@ -0,0 +1,528 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Out\Module;
use \Alchemy\Phrasea\Out\Tool\PhraseaPDF;
require_once __DIR__ . '/../../../../vendor/tcpdf/tcpdf.php';
/**
* Creates a PDF
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class PDF
{
protected $records;
protected $pdf;
const LAYOUT_PREVIEW = 'preview';
const LAYOUT_PREVIEWCAPTION = 'previewCaption';
const LAYOUT_PREVIEWCAPTIONTDM = 'previewCaptionTdm';
const LAYOUT_THUMBNAILLIST = 'thumbnailList';
const LAYOUT_THUMBNAILGRID = 'thumbnailGrid';
public function __construct(array $records, $layout)
{
$list = array();
foreach ($records as $record)
{
switch ($layout)
{
default:
throw new \Exception('Unknown layout');
break;
case self::LAYOUT_PREVIEW:
case self::LAYOUT_PREVIEWCAPTION:
case self::LAYOUT_PREVIEWCAPTIONTDM:
try
{
// exit('prout');
$subdef = $record->get_subdef('preview');
if (!$subdef->is_physically_present())
{
continue;
}
if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
continue;
$subdef = $record->get_subdef('thumbnail');
if (!$subdef->is_physically_present())
continue;
if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
continue;
}
catch (\Exception $e)
{
continue;
}
break;
case self::LAYOUT_THUMBNAILLIST:
case self::LAYOUT_THUMBNAILGRID:
try
{
$subdef = $record->get_subdef('thumbnail');
if (!$subdef->is_physically_present())
continue;
if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
throw new \Exception('Not suitable');
}
catch (\Exception $e)
{
continue;
}
break;
}
$record->set_number(count($list) + 1);
$list[] = $record;
}
$this->records = $list;
$pdf = new PhraseaPDF("P", "mm", "A4", true, 'UTF-8', false);
$pdf->SetAuthor("Phraseanet");
$pdf->SetTitle("Phraseanet Print");
$pdf->SetDisplayMode("fullpage", "single");
$this->pdf = $pdf;
switch ($layout)
{
case "preview":
$this->print_preview();
break;
case "previewCaption":
$this->print_preview();
break;
case "previewCaptionTdm":
$this->print_preview(true);
break;
case "thumbnailList":
$this->print_thumbnailList();
break;
case "thumbnailGrid":
$this->print_thumbnailGrid();
break;
}
return $this;
}
public function render()
{
$this->pdf->Close();
return $this->pdf->Output('', 'S');
}
protected function print_thumbnailGrid($links=false)
{
$appbox = \appbox::get_instance();
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$NDiapoW = 3;
$NDiapoH = 4;
$this->pdf->AddPage();
$oldMargins = $this->pdf->getMargins();
$tmargin = $oldMargins['top'];
$lmargin = $oldMargins['left'];
$bmargin = $oldMargins['bottom'];
$rmargin = $oldMargins['right'];
$this->pdf->SetLeftMargin($lmargin + 55);
$clientW = $this->pdf->getPageWidth() - $lmargin - $rmargin;
$clientH = $this->pdf->getPageHeight() - $tmargin - $bmargin;
$DiapoW = floor($clientW / $NDiapoW);
$DiapoH = floor($clientH / $NDiapoH);
$TitleH = 5;
$ImgSize = min($DiapoW, ($DiapoH - $TitleH)) - 5;
$npages = ceil(count($this->records) / ($NDiapoW * $NDiapoH));
$irow = $ipage = 0;
$icol = -1;
foreach ($this->records as $rec)
{
/* @var $rec record_adapter */
if (++$icol >= $NDiapoW)
{
$icol = 0;
if (++$irow >= $NDiapoH)
{
$irow = 0;
$ipage++;
$this->pdf->AddPage();
}
}
$fimg = null;
$himg = 0;
$subdef = $rec->get_subdef('preview');
$fimg = $subdef->get_pathfile();
if (!$user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
&& $subdef->get_type() == media_subdef::TYPE_IMAGE)
$fimg = recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
$wimg = $himg = $ImgSize;
if ($subdef->get_height() > 0 && $subdef->get_width() > 0)
{
if ($subdef->get_width() > $subdef->get_height())
$himg = $wimg * $subdef->get_height() / $subdef->get_width();
else
$wimg = $himg * $subdef->get_width() / $subdef->get_height();
}
if ($fimg)
{
$x = $lmargin + ($icol * $DiapoW);
$y = $tmargin + ($irow * $DiapoH);
$this->pdf->SetDrawColor(0);
$this->pdf->Rect($x, $y, $DiapoW, $DiapoH, "D");
$this->pdf->SetXY($x, $y + 1);
$this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
$t = $irow . '-' . $x;
$t = $rec->get_title();
$this->pdf->MultiCell($DiapoW, $TitleH, $t, '0', 'C', false);
if ($links)
{
$lk = $this->pdf->AddLink();
$this->pdf->SetLink($lk, 0, $npages + $rec->get_number());
$this->pdf->Image(
$fimg
, $x + (($DiapoW - $wimg) / 2)
, $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
, $wimg, $himg
, null, $lk
);
}
else
{
$this->pdf->Image($fimg
, $x + (($DiapoW - $wimg) / 2)
, $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
, $wimg, $himg
);
}
}
}
$this->pdf->SetLeftMargin($oldMargins['left']);
}
protected function print_thumbnailList()
{
$this->pdf->AddPage();
$oldMargins = $this->pdf->getMargins();
$tmargin = $oldMargins['top'];
$lmargin = $oldMargins['left'];
$bmargin = $oldMargins['bottom'];
$rmargin = $oldMargins['right'];
$this->pdf->SetLeftMargin($lmargin + 55);
$ndoc = 0;
$lastpage = $this->pdf->PageNo();
foreach ($this->records as $rec)
{
/* @var $rec record_adapter */
$subdef = $rec->get_subdef('thumbnail');
$fimg = $subdef->get_pathfile();
$wimg = $himg = 50;
if ($subdef->get_width() > $subdef->get_height())
$himg = round($wimg * $subdef->get_height() / $subdef->get_width());
else
$wimg = round($himg * $subdef->get_width() / $subdef->get_height());
$himg = 0;
if ($this->pdf->GetY() > $this->pdf->getPageHeight() - (6 + $himg + 20))
$this->pdf->AddPage();
$title = "record : " . $rec->get_title();
$y = $this->pdf->GetY();
$t = phrasea::bas_names($rec->get_base_id());
$this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
$this->pdf->SetFillColor(220, 220, 220);
$this->pdf->SetLeftMargin($lmargin);
$this->pdf->SetRightMargin($rmargin);
$this->pdf->SetX($lmargin);
$this->pdf->SetY($y);
$this->pdf->out = false;
$this->pdf->MultiCell(140, 4, $title, "LTR", "L", 1);
$y2 = $this->pdf->GetY();
$h = $y2 - $y;
$this->pdf->out = true;
$this->pdf->SetX($lmargin);
$this->pdf->SetY($y);
$this->pdf->Cell(0, $h, "", "LTR", 1, "R", 1);
$this->pdf->SetX($lmargin);
$this->pdf->SetY($y);
$this->pdf->Cell(0, 4, $t, "", 1, "R");
$this->pdf->SetX($lmargin);
$this->pdf->SetY($y);
$this->pdf->MultiCell(140, 4, $title, "", "L");
$this->pdf->SetX($lmargin);
$this->pdf->SetY($y = $y2);
$this->pdf->SetLeftMargin($lmargin + 55);
$this->pdf->SetY($y + 2);
if ($fimg)
{
$y = $this->pdf->GetY();
$this->pdf->Image($fimg, $lmargin, $y, $wimg, $himg);
$this->pdf->SetY($y);
}
$nf = 0;
$this->pdf->SetX($lmargin + 55);
$p0 = $this->pdf->PageNo();
$y0 = $this->pdf->GetY();
foreach ($rec->get_caption()->get_fields() as $field)
{
/* @var $field caption_field */
$this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
$this->pdf->Write(5, $field->get_name() . " : ");
$this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
$this->pdf->Write(5, $field->get_value(true));
$this->pdf->Write(6, "\n");
$nf++;
}
if ($this->pdf->PageNo() == $p0 && ($this->pdf->GetY() - $y0) < $himg)
$this->pdf->SetY($y0 + $himg);
$ndoc++;
}
$this->pdf->SetLeftMargin($lmargin);
}
protected function print_preview($withtdm=false)
{
$appbox = \appbox::get_instance();
$registry = \registry::get_instance();
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
if ($withtdm === true)
{
$this->print_thumbnailGrid($this->pdf, $this->records, true);
}
foreach ($this->records as $krec => $rec)
{
/* @var $rec record_adapter */
$this->pdf->AddPage();
if ($withtdm === "CALCPAGES")
{
if ($presentationpage)
$rec->set_number($this->pdf->PageNo() + 1);
else
$rec->set_number($this->pdf->PageNo());
}
$lmargin = $this->pdf->GetX();
$tmargin = $this->pdf->GetY();
$himg = 0;
$y = 0;
$miniConv = NULL;
$LEFT__TEXT = "";
$LEFT__IMG = NULL;
$RIGHT_TEXT = "";
$RIGHT_IMG = NULL;
$LEFT__IMG = $registry->get('GV_RootPath') . "config/minilogos/logopdf_"
. $rec->get_sbas_id() . ".jpg";
if (!is_file($LEFT__IMG))
{
$databox = $rec->get_databox();
$str = $databox->get_sxml_structure();
$vn = (string) ($str->pdfPrintLogo);
if (($vn * 1) == 1)
{
$LEFT__TEXT = $databox->get_viewname();
}
}
$collection = \collection::get_from_base_id($rec->get_base_id());
$vn = "";
if ($str = simplexml_load_string($collection->get_prefs()))
$vn = (string) ($str->pdfPrintappear);
if ($vn == "" || $vn == "1")
{
$RIGHT_TEXT = \phrasea::bas_names($rec->get_base_id());
}
elseif ($vn == "2")
{
$RIGHT_IMG = $registry->get('GV_RootPath') . "config/minilogos/" . $rec->get_base_id();
}
$xtmp = $this->pdf->GetX();
$ytmp = $this->pdf->GetY();
$this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
$this->pdf->SetFillColor(220, 220, 220);
$y = $this->pdf->GetY();
$this->pdf->MultiCell(95, 7, $LEFT__TEXT, "LTB", "L", 1);
$y2 = $this->pdf->GetY();
$h = $y2 - $y;
$this->pdf->SetY($y);
$this->pdf->SetX(105);
$this->pdf->Cell(95, $h, $RIGHT_TEXT, "TBR", 1, "R", 1);
if ($LEFT__TEXT == "" && is_file($LEFT__IMG))
{
if ($size = @getimagesize($LEFT__IMG))
{
$wmm = (int) $size[0] * 25.4 / 72;
$hmm = (int) $size[1] * 25.4 / 72;
if ($hmm > 6)
{
$coeff = $hmm / 6;
$wmm = (int) $wmm / $coeff;
$hmm = (int) $hmm / $coeff;
}
$this->pdf->Image($LEFT__IMG, $xtmp + 0.5, $ytmp + 0.5, $wmm, $hmm);
}
}
if ($RIGHT_IMG != NULL && is_file($RIGHT_IMG))
{
if ($size = @getimagesize($RIGHT_IMG))
{
if ($size[2] == '1')
{
if (!isset($miniConv[$RIGHT_IMG]))
{
$tmp_filename = tempnam('minilogos/', 'gif4fpdf');
$img = imagecreatefromgif($RIGHT_IMG);
imageinterlace($img, 0);
imagepng($img, $tmp_filename);
rename($tmp_filename, $tmp_filename . '.png');
$miniConv[$RIGHT_IMG] = $tmp_filename . '.png';
$RIGHT_IMG = $tmp_filename . '.png';
}
else
$RIGHT_IMG = $miniConv[$RIGHT_IMG];
$wmm = (int) $size[0] * 25.4 / 72;
$hmm = (int) $size[1] * 25.4 / 72;
if ($hmm > 6)
{
$coeff = $hmm / 6;
$wmm = (int) $wmm / $coeff;
$hmm = (int) $hmm / $coeff;
}
$tt = 0;
if ($hmm < 6)
$tt = (6 - $hmm) / 2;
$this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5 + $tt);
}
else
{
$wmm = (int) $size[0] * 25.4 / 72;
$hmm = (int) $size[1] * 25.4 / 72;
if ($hmm > 6)
{
$coeff = $hmm / 6;
$wmm = (int) $wmm / $coeff;
$hmm = (int) $hmm / $coeff;
}
$this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5);
}
}
}
$y = $this->pdf->GetY() + 3;
$subdef = $rec->get_subdef('preview');
$f = $subdef->get_pathfile();
if (!$user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
&& $subdef->get_type() == media_subdef::TYPE_IMAGE)
$f = recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
$wimg = $himg = 150; // preview dans un carre de 150 mm
if ($subdef->get_width() > 0 && $subdef->get_height() > 0)
{
if ($subdef->get_width() > $subdef->get_height())
$himg = $wimg * $subdef->get_height() / $subdef->get_width();
else
$wimg = $himg * $subdef->get_width() / $subdef->get_height();
}
$this->pdf->Image($f, $lmargin, $y, $wimg, $himg);
if ($miniConv != NULL)
{
foreach ($miniConv as $oneF)
unlink($oneF);
}
$this->pdf->SetXY($lmargin, $y += ( $himg + 5));
$nf = 0;
foreach ($rec->get_caption()->get_fields() as $field)
{
/* @var $field caption_field */
if ($nf > 0)
$this->pdf->Write(6, "\n");
$this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
$this->pdf->Write(5, $field->get_name() . " : ");
$this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
$t = str_replace(
array("&lt;", "&gt;", "&amp;")
, array("<", ">", "&")
, $field->get_value(true)
);
$this->pdf->Write(5, $t);
$nf++;
}
}
return;
}
}

View File

@@ -0,0 +1,54 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Out\Tool;
/**
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class PhraseaPDF extends \TCPDF
{
const FONT = 'freesans';
function Header()
{
}
function Footer()
{
$ml = $this->SetLeftMargin(0);
$mr = $this->SetRightMargin(0);
$this->SetY(-15);
$this->SetFont(self::FONT, 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
$this->SetFont(self::FONT, '', 8);
$w = $this->GetStringWidth('Printed by');
$this->SetFont(self::FONT, 'B', 8);
$w += $this->GetStringWidth(' Phraseanet');
$this->SetXY(-$w - $mr - 5, -15);
$this->SetFont(self::FONT, '', 8);
$this->Write(8, 'Printed by');
$this->SetFont(self::FONT, 'B', 8);
$this->Write(8, ' Phraseanet');
}
}

View File

@@ -20,7 +20,6 @@ require_once __DIR__ . '/../../classes/User/Adapter.class.php';
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Basket class Basket
{ {
@@ -325,7 +324,7 @@ class Basket
foreach ($this->getElements() as $basket_element) foreach ($this->getElements() as $basket_element)
{ {
$bask_record = $basket_element->getRecord(); $bask_record = $basket_element->getRecord();
if ($bask_record->get_record_id() == $record->get_record_id() if ($bask_record->get_record_id() == $record->get_record_id()
&& $bask_record->get_sbas_id() == $record->get_sbas_id()) && $bask_record->get_sbas_id() == $record->get_sbas_id())
{ {
@@ -336,4 +335,27 @@ class Basket
return false; return false;
} }
public function getSize()
{
$totSize = 0;
foreach ($this->getElements() as $basket_element)
{
try
{
$totSize += $basket_element->getRecord()
->get_subdef('document')
->get_size();
}
catch (Exception $e)
{
}
}
$totSize = round($totSize / (1024 * 1024), 2);
return $totSize;
}
} }

View File

@@ -22,214 +22,235 @@ require_once __DIR__ . '/../../classes/record/adapter.class.php';
*/ */
class BasketElement class BasketElement
{ {
/**
* @var integer $id
*/
private $id;
/** /**
* @var integer $record_id * @var integer $id
*/ */
private $record_id; private $id;
/** /**
* @var integer $sbas_id * @var integer $record_id
*/ */
private $sbas_id; private $record_id;
/** /**
* @var integer $ord * @var integer $sbas_id
*/ */
private $ord; private $sbas_id;
/** /**
* @var datetime $created * @var integer $ord
*/ */
private $created; private $ord;
/** /**
* @var datetime $updated * @var datetime $created
*/ */
private $updated; private $created;
/** /**
* @var Entities\Basket * @var datetime $updated
*/ */
private $basket; private $updated;
/**
* @var Entities\Basket
*/
private $basket;
/** /**
* Get id * Get id
* *
* @return integer * @return integer
*/ */
public function getId() public function getId()
{
return $this->id;
}
/**
* Set record_id
*
* @param integer $recordId
*/
public function setRecordId($recordId)
{
$this->record_id = $recordId;
}
/**
* Get record_id
*
* @return integer
*/
public function getRecordId()
{
return $this->record_id;
}
/**
* Set sbas_id
*
* @param integer $sbasId
*/
public function setSbasId($sbasId)
{
$this->sbas_id = $sbasId;
}
/**
* Get sbas_id
*
* @return integer
*/
public function getSbasId()
{
return $this->sbas_id;
}
/**
* Set ord
*
* @param integer $ord
*/
public function setOrd($ord)
{
$this->ord = $ord;
}
/**
* Get ord
*
* @return integer
*/
public function getOrd()
{
return $this->ord;
}
/**
* Set created
*
* @param datetime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* Get created
*
* @return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* @param datetime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* Get updated
*
* @return datetime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set basket
*
* @param Entities\Basket $basket
*/
public function setBasket(\Entities\Basket $basket)
{
$this->basket = $basket;
}
/**
* Get basket
*
* @return Entities\Basket
*/
public function getBasket()
{
return $this->basket;
}
public function getRecord()
{
return new \record_adapter($this->getSbasId(), $this->getRecordId(), $this->getOrd());
}
public function setRecord(\record_adapter $record)
{
$this->setRecordId($record->get_record_id());
$this->setSbasId($record->get_sbas_id());
}
public function setLastInBasket()
{
$this->setOrd($this->getBasket()->getElements()->count() + 1);
}
/**
* @var Entities\ValidationData
*/
private $validation_datas;
public function __construct()
{
$this->validation_datas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add validation_datas
*
* @param Entities\ValidationData $validationDatas
*/
public function addValidationData(\Entities\ValidationData $validationDatas)
{
$this->validation_datas[] = $validationDatas;
}
/**
* Get validation_datas
*
* @return Doctrine\Common\Collections\Collection
*/
public function getValidationDatas()
{
return $this->validation_datas;
}
/**
*
* @param \User_Adapter $user
* @return \Entities\ValidationData
*/
public function getUserValidationDatas(\User_Adapter $user)
{
foreach ($this->validation_datas as $validationData)
{ {
return $this->id; /* @var $validationData \Entities\ValidationData */
if ($validationData->getParticipant()->getUser()->get_id() == $user->get_id())
{
return $validationData;
}
} }
/** throw new \Exception('There is no such participant');
* Set record_id }
*
* @param integer $recordId
*/
public function setRecordId($recordId)
{
$this->record_id = $recordId;
}
/**
* Get record_id
*
* @return integer
*/
public function getRecordId()
{
return $this->record_id;
}
/**
* Set sbas_id
*
* @param integer $sbasId
*/
public function setSbasId($sbasId)
{
$this->sbas_id = $sbasId;
}
/**
* Get sbas_id
*
* @return integer
*/
public function getSbasId()
{
return $this->sbas_id;
}
/**
* Set ord
*
* @param integer $ord
*/
public function setOrd($ord)
{
$this->ord = $ord;
}
/**
* Get ord
*
* @return integer
*/
public function getOrd()
{
return $this->ord;
}
/**
* Set created
*
* @param datetime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* Get created
*
* @return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* @param datetime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* Get updated
*
* @return datetime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set basket
*
* @param Entities\Basket $basket
*/
public function setBasket(\Entities\Basket $basket)
{
$this->basket = $basket;
}
/**
* Get basket
*
* @return Entities\Basket
*/
public function getBasket()
{
return $this->basket;
}
public function getRecord()
{
return new \record_adapter($this->getSbasId(), $this->getRecordId(), $this->getOrd());
}
public function setRecord(\record_adapter $record)
{
$this->setRecordId($record->get_record_id());
$this->setSbasId($record->get_sbas_id());
}
public function setLastInBasket()
{
$this->setOrd($this->getBasket()->getElements()->count() + 1);
}
/**
* @var Entities\ValidationData
*/
private $validation_datas;
public function __construct()
{
$this->validation_datas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add validation_datas
*
* @param Entities\ValidationData $validationDatas
*/
public function addValidationData(\Entities\ValidationData $validationDatas)
{
$this->validation_datas[] = $validationDatas;
}
/**
* Get validation_datas
*
* @return Doctrine\Common\Collections\Collection
*/
public function getValidationDatas()
{
return $this->validation_datas;
}
} }

View File

@@ -8,7 +8,9 @@
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Entities; namespace Entities;
/** /**
* *
* @package * @package
@@ -28,19 +30,44 @@ class ValidationParticipant
*/ */
private $usr_id; private $usr_id;
/**
* @var Entities\ValidationData
*/
private $datases;
/** /**
* @var Entities\ValidationSession * @var Entities\ValidationSession
*/ */
private $session; private $session;
/**
* @var datetime $reminded
*/
private $reminded = null;
/**
* @var Entities\ValidationData
*/
private $datas;
/**
* @var boolean $is_confirmed
*/
private $is_confirmed = false;
/**
* @var boolean $can_agree
*/
private $can_agree = false;
/**
* @var boolean $can_see_others
*/
private $can_see_others = false;
/**
* @var boolean $is_aware
*/
private $is_aware = false;
public function __construct() public function __construct()
{ {
$this->datases = new \Doctrine\Common\Collections\ArrayCollection(); $this->datas = new \Doctrine\Common\Collections\ArrayCollection();
} }
/** /**
@@ -76,21 +103,11 @@ class ValidationParticipant
/** /**
* Add datases * Add datases
* *
* @param Entities\ValidationData $datases * @param Entities\ValidationData $datas
*/ */
public function addValidationData(\Entities\ValidationData $datases) public function addValidationData(\Entities\ValidationData $datas)
{ {
$this->datases[] = $datases; $this->datas[] = $datas;
}
/**
* Get datases
*
* @return Doctrine\Common\Collections\Collection
*/
public function getDatases()
{
return $this->datases;
} }
/** /**
@@ -113,12 +130,6 @@ class ValidationParticipant
return $this->session; return $this->session;
} }
/**
* @var boolean $is_aware
*/
private $is_aware = false;
/** /**
* Set is_aware * Set is_aware
* *
@@ -144,10 +155,125 @@ class ValidationParticipant
* @param \User_Adapter $user * @param \User_Adapter $user
* @return ValidationParticipant * @return ValidationParticipant
*/ */
public function setParticipant(\User_Adapter $user) public function setUser(\User_Adapter $user)
{ {
$this->usr_id = $user->get_id(); $this->usr_id = $user->get_id();
return $this; return $this;
} }
public function getUser()
{
return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance());
}
/**
* Set reminded
*
* @param datetime $reminded
*/
public function setReminded($reminded)
{
$this->reminded = $reminded;
}
/**
* Get reminded
*
* @return datetime
*/
public function getReminded()
{
return $this->reminded;
}
/**
* Get datas
*
* @return Doctrine\Common\Collections\Collection
*/
public function getDatas()
{
return $this->datas;
}
/**
* Set is_confirmed
*
* @param boolean $isConfirmed
*/
public function setIsConfirmed($isConfirmed)
{
$this->is_confirmed = $isConfirmed;
}
/**
* Get is_confirmed
*
* @return boolean
*/
public function getIsConfirmed()
{
return $this->is_confirmed;
}
/**
* Set can_agree
*
* @param boolean $canAgree
*/
public function setCanAgree($canAgree)
{
$this->can_agree = $canAgree;
}
/**
* Get can_agree
*
* @return boolean
*/
public function getCanAgree()
{
return $this->can_agree;
}
/**
* Set can_see_others
*
* @param boolean $canSeeOthers
*/
public function setCanSeeOthers($canSeeOthers)
{
$this->can_see_others = $canSeeOthers;
}
/**
* Get can_see_others
*
* @return boolean
*/
public function getCanSeeOthers()
{
return $this->can_see_others;
}
public function isReleasable()
{
if ($this->getIsConfirmed())
{
return false;
}
foreach ($this->getDatas() as $validation_data)
{
/* @var $validation_data \Entities\ValidationData */
if ($validation_data->getAgreement() === null)
{
return false;
}
}
return true;
}
} }

View File

@@ -265,6 +265,24 @@ class ValidationSession
return $this->participants; return $this->participants;
} }
/**
* Get a participant
*
* @return Entities\ValidationParticipant
*/
public function getParticipant(\User_Adapter $user)
{
foreach ($this->getParticipants() as $participant)
{
if ($participant->getUser()->get_id() == $user->get_id())
{
return $participant;
}
}
throw new \Exception_NotFound('Particpant not found');
}
/** /**
* @var integer $initiator * @var integer $initiator
*/ */
@@ -295,6 +313,11 @@ class ValidationSession
return $this->initiator_id; return $this->initiator_id;
} }
public function isInitiator(\User_Adapter $user)
{
return $this->getInitiatorId() == $user->get_id();
}
public function setInitiator(\User_Adapter $user) public function setInitiator(\User_Adapter $user)
{ {
$this->initiator_id = $user->get_id(); $this->initiator_id = $user->get_id();
@@ -309,4 +332,55 @@ class ValidationSession
} }
} }
public function isFinished()
{
if (is_null($this->getExpires()))
{
return null;
}
$date_obj = new DateTime();
return $date_obj > $this->getExpires();
}
public function getValidationString(\User_Adapter $user)
{
if ($this->isInitiator($user))
{
if ($this->isFinished())
{
return sprintf(
_('Vous aviez envoye cette demande a %d utilisateurs')
, (count($this->getParticipants()) - 1)
);
}
else
{
return sprintf(
_('Vous avez envoye cette demande a %d utilisateurs')
, (count($this->getParticipants()) - 1)
);
}
}
else
{
if ($this->getParticipant($user)->getCanSeeOthers())
{
return sprintf(
_('Processus de validation recu de %s et concernant %d utilisateurs')
, $this->getInitiator()->get_display_name()
, (count($this->getParticipants()) - 1));
}
else
{
return sprintf(
_('Processus de validation recu de %s')
, $this->getInitiator()->get_display_name()
);
}
}
}
} }

View File

@@ -0,0 +1,92 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Doctrine\Logger;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
/**
* Log doctrine sql request with monolog
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class MonologSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger
{
const JSON = 'json';
const YAML = 'yaml';
const NORMAL = 'normal';
/**
*
* @var \Monolog\Logger
*/
private $logger;
private $start;
private $output = array();
private $outputType;
/**
* Tell which monolog user to use and which format to output
*
* @param \Monolog\Logger $logger A monolog logger instance
* @param type $type the output format
*/
public function __construct(\Monolog\Logger $logger, $type = self::YAML)
{
$this->logger = $logger;
$this->outputType = $type;
}
/**
* {@inheritdoc}
*/
public function startQuery($sql, array $params = null, array $types = null)
{
$this->start = microtime(true);
$this->output["sql"] = $sql;
if ($params)
{
$this->output["params"] = $params;
}
}
/**
* {@inheritdoc}
*/
public function stopQuery()
{
$mstime = microtime(true) - $this->start;
$this->output["times"] = $mstime . " seconds";
if ($this->outputType == self::JSON)
{
$this->log(json_encode($this->output));
}
elseif ($this->outputType == self::YAML)
{
$this->log(\Symfony\Component\Yaml\Yaml::dump($this->output));
}
else
{
$this->log(var_export($this->output, true));
}
}
protected function log($message)
{
$this->logger->debug($message);
}
}

View File

@@ -192,6 +192,12 @@ class EntitiesBasketProxy extends \Entities\Basket implements \Doctrine\ORM\Prox
return parent::hasRecord($record); return parent::hasRecord($record);
} }
public function getSize()
{
$this->__load();
return parent::getSize();
}
public function __sleep() public function __sleep()
{ {

View File

@@ -0,0 +1,119 @@
<?php
namespace Repositories;
use Doctrine\ORM\EntityRepository;
/**
* BasketElementRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class BasketElementRepository extends EntityRepository
{
public function findUserElement($element_id, \User_Adapter $user)
{
$dql = 'SELECT e FROM Entities\BasketElement e
JOIN e.basket b
WHERE b.usr_id = :usr_id AND e.id = :element_id';
$params = array(
'usr_id' => $user->get_id(),
'element_id' => $element_id
);
$query = $this->_em->createQuery($dql);
$query->setParameters($params);
return $query->getOneOrNullResult();
}
public function findElementsByRecord(\record_adapter $record)
{
$dql = 'SELECT e FROM Entities\BasketElement e
WHERE e.record_id = :record_id AND e.sbas_id = :sbas_id';
$params = array(
'sbas_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id()
);
$query = $this->_em->createQuery($dql);
$query->setParameters($params);
return $query->getResult();
}
/**
*
* @param \record_adapter $record
* @param \User_Adapter $user
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function findReceivedElementsByRecord(\record_adapter $record, \User_Adapter $user)
{
$dql = 'SELECT e FROM Entities\BasketElement e
JOIN e.basket b
WHERE b.usr_id = :usr_id AND b.pusher_id IS NOT NULL
AND e.record_id = :record_id AND e.sbas_id = :sbas_id';
$params = array(
'sbas_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id(),
'usr_id' => $user->get_id()
);
$query = $this->_em->createQuery($dql);
$query->setParameters($params);
return $query->getResult();
}
public function findReceivedValidationElementsByRecord(\record_adapter $record, \User_Adapter $user)
{
$dql = 'SELECT e FROM Entities\BasketElement e
JOIN e.basket b
JOIN b.validation v
JOIN v.participants p
WHERE p.usr_id = :usr_id
AND e.record_id = :record_id AND e.sbas_id = :sbas_id';
$params = array(
'sbas_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id(),
'usr_id' => $user->get_id()
);
$query = $this->_em->createQuery($dql);
$query->setParameters($params);
return $query->getResult();
}
/**
*
* @param type $element_id
* @param \User_Adapter $user
* @return \Entities\BasketELement
*/
public function findElement($element_id, \User_Adapter $user)
{
$element = $this->find($element_id);
/* @var $element \Entities\BasketElement */
if (null === $element)
{
throw new \Exception_NotFound(_('Element is not found'));
}
if ($element->getBasket()->getowner()->get_id() != $user->get_id())
{
throw new \Exception_Forbidden(_('You have not access to this basket element'));
}
return $element;
}
}

View File

@@ -32,14 +32,31 @@ class BasketRepository extends EntityRepository
{ {
$dql = 'SELECT b FROM Entities\Basket b $dql = 'SELECT b FROM Entities\Basket b
WHERE b.usr_id = :usr_id AND b.archived = false'; WHERE b.usr_id = :usr_id AND b.archived = false';
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
$query->setParameters(array('usr_id' => $user->get_id())); $query->setParameters(array('usr_id' => $user->get_id()));
return $query->getResult(); return $query->getResult();
} }
/**
* Returns all unread basket for a given user that are not marked as archived
*
* @param \User_Adapter $user
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function findUnreadActiveByUser(\User_Adapter $user)
{
$dql = 'SELECT b FROM Entities\Basket b
WHERE b.usr_id = :usr_id
AND b.archived = false AND b.is_read = false';
$query = $this->_em->createQuery($dql);
$query->setParameters(array('usr_id' => $user->get_id()));
return $query->getResult();
}
/** /**
* Returns all baskets that are in validation session not expired and * Returns all baskets that are in validation session not expired and
* where a specified user is participant (not owner) * where a specified user is participant (not owner)
@@ -54,18 +71,27 @@ class BasketRepository extends EntityRepository
JOIN s.participants p JOIN s.participants p
WHERE b.usr_id != ?1 AND p.usr_id = ?2 WHERE b.usr_id != ?1 AND p.usr_id = ?2
AND s.expires > CURRENT_TIMESTAMP()'; AND s.expires > CURRENT_TIMESTAMP()';
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
$query->setParameters(array(1 => $user->get_id(), 2 => $user->get_id())); $query->setParameters(array(1 => $user->get_id(), 2 => $user->get_id()));
return $query->getResult(); return $query->getResult();
} }
/**
* Find a basket specified by his basket_id and his owner
*
* @throws \Exception_NotFound
* @throws \Exception_Forbidden
* @param type $basket_id
* @param \User_Adapter $user
* @return \Entities\Basket
*/
public function findUserBasket($basket_id, \User_Adapter $user) public function findUserBasket($basket_id, \User_Adapter $user)
{ {
$basket = $this->find($basket_id); $basket = $this->find($basket_id);
/* @var $basket Entities\Basket */ /* @var $basket \Entities\Basket */
if (null === $basket) if (null === $basket)
{ {
throw new \Exception_NotFound(_('Basket is not found')); throw new \Exception_NotFound(_('Basket is not found'));
@@ -79,4 +105,21 @@ class BasketRepository extends EntityRepository
return $basket; return $basket;
} }
public function findContainingRecord(\record_adapter $record)
{
$dql = 'SELECT b FROM Entities\Basket b
JOIN b.elements e
WHERE e.record_id = :record_id AND e.sbas_id = e.sbas_id';
$params = array(
'record_id' => $record->get_record_id()
);
$query = $this->_em->createQuery($dql);
$query->setParameters($params);
return $query->getResult();
}
} }

View File

@@ -20,7 +20,7 @@ class StoryWZRepository extends EntityRepository
public function findUserStory(\User_Adapter $user, \record_adapter $Story) public function findUserStory(\User_Adapter $user, \record_adapter $Story)
{ {
return $this->findBy( return $this->findOneBy(
array( array(
'usr_id' => $user->get_id(), 'usr_id' => $user->get_id(),
'sbas_id' => $Story->get_sbas_id(), 'sbas_id' => $Story->get_sbas_id(),

View File

@@ -11,9 +11,10 @@
/** /**
* *
* @package * @return \Alchemy\Phrasea\Core
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
require_once dirname(__FILE__) . '/classes/bootstrap.class.php'; require_once dirname(__FILE__) . '/classes/bootstrap.class.php';
bootstrap::execute();
return bootstrap::execute();

View File

@@ -47,6 +47,7 @@ class ACL implements cache_cacheableInterface
* @var Array * @var Array
*/ */
protected $_rights_records_preview; protected $_rights_records_preview;
/** /**
* *
* @var Array * @var Array
@@ -242,47 +243,88 @@ class ACL implements cache_cacheableInterface
if (count($base_ids) == 0) if (count($base_ids) == 0)
return $this; return $this;
$params = array( $sbas_ids = array();
':usr_id' => $this->user->get_id()
, ':template_id' => $template_user->get_id() foreach ($base_ids as $base_id)
{
$sbas_ids[] = phrasea::sbasFromBas($base_id);
}
$sbas_ids = array_unique($sbas_ids);
$sbas_rights = array('bas_manage', 'bas_modify_struct', 'bas_modif_th', 'bas_chupub');
$sbas_to_acces = array();
$rights_to_give = array();
foreach ($template_user->ACL()->get_granted_sbas() as $databox)
{
$sbas_id = $databox->get_sbas_id();
if (!in_array($sbas_id, $sbas_ids))
continue;
if (!$this->has_access_to_sbas($sbas_id))
{
$sbas_to_acces[] = $sbas_id;
}
foreach ($sbas_rights as $right)
{
if ($template_user->ACL()->has_right_on_sbas($sbas_id, $right))
{
$rights_to_give[$sbas_id][$right] = '1';
}
}
}
$this->give_access_to_sbas($sbas_to_acces);
foreach ($rights_to_give as $sbas_id => $rights)
{
$this->update_rights_to_sbas($sbas_id, $rights);
}
$bas_rights = array('canputinalbum', 'candwnldhd'
, 'candwnldpreview', 'cancmd'
, 'canadmin', 'actif', 'canreport', 'canpush'
, 'canaddrecord', 'canmodifrecord', 'candeleterecord'
, 'chgstatus', 'imgtools'
, 'manage', 'modify_struct'
, 'nowatermark', 'order_master'
); );
$sql = 'INSERT INTO sbasusr $bas_to_acces = array();
(SELECT distinct null as sbasusr_id, sb.sbas_id, :usr_id as usr_id, bas_manage $rights_to_give = array();
, bas_modify_struct,bas_modif_th,bas_chupub
FROM sbasusr sb, bas b
WHERE b.base_id IN (' . implode(', ', $base_ids) . ')
AND b.sbas_id = sb.sbas_id
AND usr_id = :template_id)';
$stmt = $this->appbox->get_connection()->prepare($sql); foreach ($template_user->ACL()->get_granted_base() as $collection)
$stmt->execute($params); {
$stmt->closeCursor(); $base_id = $collection->get_base_id();
$this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS); if (!in_array($base_id, $base_ids))
continue;
$sql = "INSERT INTO basusr if (!$this->has_access_to_base($base_id))
(SELECT null as id, base_id, :usr_id as usr_id, canputinalbum {
, candwnldhd, candwnldsubdef, candwnldpreview, cancmd $bas_to_acces[] = $base_id;
, canadmin, actif, canreport, canpush, now() as creationdate }
, basusr_infousr, mask_and, mask_xor, restrict_dwnld
, month_dwnld_max, remain_dwnld, time_limited, limited_from
, limited_to, canaddrecord, canmodifrecord, candeleterecord
, chgstatus, '0000-00-00 00:00:00' as lastconn, imgtools
, manage, modify_struct, bas_manage, bas_modify_struct
, nowatermark, order_master
FROM basusr
WHERE usr_id =
(SELECT usr_id
FROM usr WHERE usr_id = :template_id)
AND base_id IN (" . implode(', ', $base_ids) . "))";
$stmt = $this->appbox->get_connection()->prepare($sql); foreach ($bas_rights as $right)
$stmt->execute($params); {
$stmt->closeCursor(); if ($template_user->ACL()->has_right_on_base($base_id, $right))
{
$rights_to_give[$base_id][$right] = '1';
}
}
}
$this->inject_rights(); $this->give_access_to_base($bas_to_acces);
$this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
foreach ($rights_to_give as $sbas_id => $rights)
{
$this->update_rights_to_base($base_id, $rights);
}
$this->user->set_last_template($template_user); $this->user->set_last_template($template_user);
@@ -315,7 +357,7 @@ class ACL implements cache_cacheableInterface
{ {
return false; return false;
} }
if (!isset($this->_rights_bas[$base_id][$right])) if (!isset($this->_rights_bas[$base_id][$right]))
throw new Exception('right ' . $right . ' does not exists'); throw new Exception('right ' . $right . ' does not exists');
@@ -750,7 +792,7 @@ class ACL implements cache_cacheableInterface
{ {
if ($this->_rights_bas && $this->_global_rights && is_array($this->_limited)) if ($this->_rights_bas && $this->_global_rights && is_array($this->_limited))
return $this; return $this;
try try
{ {
$this->_rights_bas = $this->get_data_from_cache(self::CACHE_RIGHTS_BAS); $this->_rights_bas = $this->get_data_from_cache(self::CACHE_RIGHTS_BAS);
@@ -1399,12 +1441,12 @@ class ACL implements cache_cacheableInterface
$this->load_rights_bas(); $this->load_rights_bas();
$datetime = new DateTime(); $datetime = new DateTime();
if (!isset($this->_limited[$base_id])) if (!isset($this->_limited[$base_id]))
{ {
return false; return false;
} }
$ret = ($this->_limited[$base_id]['dmin'] > $datetime $ret = ($this->_limited[$base_id]['dmin'] > $datetime
|| $this->_limited[$base_id]['dmax'] < $datetime); || $this->_limited[$base_id]['dmax'] < $datetime);

View File

@@ -9,7 +9,7 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
require_once dirname(__FILE__) . '/../../../vendor/oauth2/lib/OAuth2.inc'; require_once __DIR__ . '/../../../vendor/oauth2/lib/OAuth2.inc';
/** /**
* *

View File

@@ -41,7 +41,7 @@ class API_OAuth2_Autoloader
*/ */
static public function autoload($class) static public function autoload($class)
{ {
if (file_exists($file = dirname(__FILE__) . '/../../../vendor/oauth2/lib/' . str_replace(array('_', "\0"), array('/', ''), $class) . '.inc')) if (file_exists($file = __DIR__ . '/../../../vendor/oauth2/lib/' . str_replace(array('_', "\0"), array('/', ''), $class) . '.inc'))
{ {
require $file; require $file;
} }

View File

@@ -34,6 +34,13 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
protected $appbox; protected $appbox;
/**
* Phraseanet Core
*
* @var \Alchemy\Phrasea\Core
*/
protected $core;
/** /**
* API constructor * API constructor
* *
@@ -41,9 +48,10 @@ class API_V1_adapter extends API_V1_Abstract
* @param appbox $appbox Appbox object * @param appbox $appbox Appbox object
* @return API_V1_adapter * @return API_V1_adapter
*/ */
public function __construct($auth_token, appbox &$appbox) public function __construct($auth_token, appbox &$appbox, Alchemy\Phrasea\Core $core)
{ {
$this->appbox = $appbox; $this->appbox = $appbox;
$this->core = $core;
return $this; return $this;
} }
@@ -332,7 +340,7 @@ class API_V1_adapter extends API_V1_Abstract
$ret = array(); $ret = array();
foreach ($containers as $basket) foreach ($containers as $basket)
{ {
$ret[$basket->get_ssel_id()] = $this->list_basket($basket); $ret[$basket->getId()] = $this->list_basket($basket);
} }
$result->set_datas(array("baskets" => $ret)); $result->set_datas(array("baskets" => $ret));
@@ -549,7 +557,7 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
public function add_record_tobasket(Request $request, $databox_id, $record_id) public function add_record_tobasket(Request $request, $databox_id, $record_id)
{ {
} }
/** /**
@@ -577,16 +585,16 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
protected function list_baskets($usr_id) protected function list_baskets($usr_id)
{ {
$basket_coll = new basketCollection($this->appbox, $usr_id); $em = $this->core->getEntityManager();
$repo = $em->getRepository('\Entities\Basket');
/* @var $repo \Repositories\BasketRepository */
$baskets = $repo->findActiveByUser($this->core->getAuthenticatedUser());
$ret = array(); $ret = array();
foreach ($basket_coll->get_baskets() as $basktype => $baskets) foreach ($baskets as $basket)
{ {
if (!in_array($basktype, array('recept', 'baskets'))) $ret[$basket->getId()] = $this->list_basket($basket);
continue;
foreach ($baskets as $basket)
$ret[$basket->get_ssel_id()] = $this->list_basket($basket);
} }
return $ret; return $ret;
@@ -607,10 +615,18 @@ class API_V1_adapter extends API_V1_Abstract
if (trim(strip_tags($name)) === '') if (trim(strip_tags($name)) === '')
throw new API_V1_exception_badrequest (); throw new API_V1_exception_badrequest ();
$user = User_Adapter::getInstance($this->appbox->get_session()->get_usr_id(), $this->appbox); $user = $this->core->getAuthenticatedUser();
$basket = basket_adapter::create($this->appbox, $name, $user);
$Basket = new \Entities\Basket();
$Basket->setOwner($user);
$Basket->setName($name);
$em = $this->core->getEntityManager();
$em->persist($Basket);
$em->flush();
$ret = array(); $ret = array();
$ret[$basket->get_ssel_id()] = $this->list_basket($basket); $ret[$Basket->getId()] = $this->list_basket($Basket);
$result->set_datas(array("basket" => $ret)); $result->set_datas(array("basket" => $ret));
return $result; return $result;
@@ -627,12 +643,15 @@ class API_V1_adapter extends API_V1_Abstract
{ {
$result = new API_V1_result($request, $this); $result = new API_V1_result($request, $this);
$basket = basket_adapter::getInstance( $em = $this->core->getEntityManager();
$this->appbox $repository = $em->getRepository('\Entities\Basket');
, $basket_id
, $this->appbox->get_session()->get_usr_id()
); /* @var $repository \Repositories\BasketRepository */
$basket->delete();
$Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser());
$em->remove($Basket);
$em->flush();
return $this->search_baskets($request); return $this->search_baskets($request);
} }
@@ -647,21 +666,21 @@ class API_V1_adapter extends API_V1_Abstract
public function get_basket(Request $request, $basket_id) public function get_basket(Request $request, $basket_id)
{ {
$result = new API_V1_result($request, $this); $result = new API_V1_result($request, $this);
try
{
$basket = basket_adapter::getInstance($this->appbox, $basket_id, $this->appbox->get_session()->get_usr_id());
$result->set_datas(
array("basket_elements" =>
array(
$basket->get_ssel_id() => $this->list_basket_content($basket)
)
)
);
}
catch (Exception $e)
{
} $em = $this->core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser());
$result->set_datas(
array("basket_elements" =>
array(
$Basket->getId() => $this->list_basket_content($Basket)
)
)
);
return $result; return $result;
} }
@@ -669,16 +688,18 @@ class API_V1_adapter extends API_V1_Abstract
/** /**
* Retrieve elements of one basket * Retrieve elements of one basket
* *
* @param basket_adapter $basket * @param \Entities\Basket $Basket
* @return type * @return type
*/ */
protected function list_basket_content(basket_adapter $basket) protected function list_basket_content(\Entities\Basket $Basket)
{ {
$ret = $this->list_basket($basket); $ret = $this->list_basket($Basket);
$ret['basket_elements'] = array(); $ret['basket_elements'] = array();
foreach ($basket->get_elements() as $basket_element)
foreach ($Basket->getElements() as $basket_element)
{ {
$ret['basket_elements'][$basket_element->get_sselcont_id()] = $this->list_basket_element($basket_element); $ret['basket_elements'][$basket_element->getId()] = $this->list_basket_element($basket_element);
} }
return $ret; return $ret;
@@ -687,23 +708,46 @@ class API_V1_adapter extends API_V1_Abstract
/** /**
* Retrieve detailled informations about a basket element * Retrieve detailled informations about a basket element
* *
* @param basket_element_adapter $basket_element * @param \Entities\BasketElement $basket_element
* @return type * @return type
*/ */
protected function list_basket_element(basket_element_adapter $basket_element) protected function list_basket_element(\Entities\BasketElement $basket_element)
{ {
$ret = array( $ret = array(
'basket_element_id' => $basket_element->get_sselcont_id() 'basket_element_id' => $basket_element->getId()
, 'order' => $basket_element->get_order() , 'order' => $basket_element->getOrd()
, 'record' => $this->list_record($basket_element->get_record()) , 'record' => $this->list_record($basket_element->getRecord())
, 'validation_item' => $basket_element->is_validation_item() , 'validation_item' => !!$basket_element->getValidationDatas()
); );
if ($basket_element->is_validation_item()) if ($basket_element->getValidationDatas())
{ {
$ret['choices'] = $basket_element->get_choices(); $choices = array();
$ret['agreement'] = $basket_element->get_my_agreement(); $agreement = $note = null;
$ret['note'] = $basket_element->get_my_note();
foreach ($basket_element->getValidationDatas() as $validation_datas)
{
$user = $validation_datas->getParticipant()->getUser();
/* @var $validation_datas Entities\ValidationData */
$choices[$user->get_id()] = array(
'usr_id' => $user->get_id(),
'usr_name' => $user->get_display_name(),
'is_mine' => $user->get_id() == $this->core->getAuthenticatedUser()->get_id(),
'agreement' => $validation_datas->getAgreement(),
'updated_on' => $validation_datas->getUpdated()->format(DATE_ATOM),
'note' => $validation_datas->getNote()
);
if($user->get_id() == $this->core->getAuthenticatedUser()->get_id())
{
$agreement = $validation_datas->getAgreement();
$note = $validation_datas->getNote();
}
}
$ret['choices'] = $choices();
$ret['agreement'] = $agreement();
$ret['note'] = $note();
} }
return $ret; return $ret;
@@ -721,12 +765,23 @@ class API_V1_adapter extends API_V1_Abstract
$result = new API_V1_result($request, $this); $result = new API_V1_result($request, $this);
$name = $request->get('name'); $name = $request->get('name');
$basket = basket_adapter::getInstance($this->appbox, $basket_id, $this->appbox->get_session()->get_usr_id());
$basket->set_name($name); $em = $this->core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser());
$Basket->setName($name);
$em->merge($Basket);
$em->flush();
$result->set_datas( $result->set_datas(
array( array(
"basket" => "basket" =>
array($basket->get_ssel_id() => $this->list_basket_content($basket) array($Basket->getId() => $this->list_basket_content($Basket)
) )
) )
); );
@@ -746,12 +801,23 @@ class API_V1_adapter extends API_V1_Abstract
$result = new API_V1_result($request, $this); $result = new API_V1_result($request, $this);
$desc = $request->get('description'); $desc = $request->get('description');
$basket = basket_adapter::getInstance($this->appbox, $basket_id, $this->appbox->get_session()->get_usr_id());
$basket->set_description($desc); $em = $this->core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
/* @var $repository \Repositories\BasketRepository */
$Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser());
$Basket->setDescription($desc);
$em->merge($Basket);
$em->flush();
$result->set_datas( $result->set_datas(
array( array(
"basket" => "basket" =>
array($basket->get_ssel_id() => $this->list_basket_content($basket) array($Basket->getId() => $this->list_basket_content($Basket)
) )
) )
); );
@@ -791,7 +857,7 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
public function remove_publications(Request $request, $publication_id) public function remove_publications(Request $request, $publication_id)
{ {
} }
/** /**
@@ -919,7 +985,7 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
public function search_users(Request $request) public function search_users(Request $request)
{ {
} }
/** /**
@@ -929,7 +995,7 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
public function get_user_acces(Request $request, $usr_id) public function get_user_acces(Request $request, $usr_id)
{ {
} }
/** /**
@@ -938,7 +1004,7 @@ class API_V1_adapter extends API_V1_Abstract
*/ */
public function add_user(Request $request) public function add_user(Request $request)
{ {
} }
/** /**
@@ -1032,7 +1098,6 @@ class API_V1_adapter extends API_V1_Abstract
* @todo ajouter une option pour avoir les values serialisées * @todo ajouter une option pour avoir les values serialisées
* dans un cas multi * dans un cas multi
*/ */
return array( return array(
'meta_id' => $field->get_meta_id() 'meta_id' => $field->get_meta_id()
, 'meta_structure_id' => $field->get_meta_struct_id() , 'meta_structure_id' => $field->get_meta_struct_id()
@@ -1044,30 +1109,53 @@ class API_V1_adapter extends API_V1_Abstract
/** /**
* Retirve information about one basket * Retirve information about one basket
* *
* @param basket_adapter $basket * @param \Entities\Basket $basket
* @return array * @return array
*/ */
protected function list_basket(basket_adapter $basket) protected function list_basket(\Entities\Basket $basket)
{ {
$ret = array( $ret = array(
'created_on' => $basket->get_create_date()->format(DATE_ATOM) 'created_on' => $basket->getCreated()->format(DATE_ATOM)
, 'description' => $basket->get_description() , 'description' => (string) $basket->getDescription()
, 'name' => $basket->get_name() , 'name' => $basket->getName()
, 'pusher_usr_id' => $basket->get_pusher() ? $basket->get_pusher()->get_id() : null , 'pusher_usr_id' => $basket->getPusherId()
, 'ssel_id' => $basket->get_ssel_id() , 'ssel_id' => $basket->getId()
, 'updated_on' => $basket->get_update_date()->format(DATE_ATOM) , 'updated_on' => $basket->getUpdated()->format(DATE_ATOM)
, 'unread' => $basket->is_unread() , 'unread' => !$basket->getIsRead()
); );
if ($basket->is_valid()) if ($basket->getValidation())
{ {
$users = array();
foreach ($basket->getValidation()->getParticipants() as $participant)
{
/* @var $participant \Entities\ValidationParticipant */
$user = $participant->getUser();
$users[$user->get_id()] = array(
'usr_id' => $user->get_id(),
'usr_name' => $user->get_display_name(),
'confirmed' => $participant->getIsConfirmed(),
'can_agree' => $participant->getCanAgree(),
'can_see_others' => $participant->getCanSeeOthers()
);
}
$expires_on_atom = $basket->getValidation()->getExpires();
if ($expires_on_atom instanceof DateTime)
$expires_on_atom = $expires_on_atom->format(DATE_ATOM);
$user = \User_Adapter::getInstance($this->appbox->get_session()->get_usr_id(), $this->appbox);
$ret = array_merge( $ret = array_merge(
array( array(
'validation_users' => $basket->get_validating_users() 'validation_users' => $users
, 'validation_end_date' => ($basket->get_validation_end_date() instanceof DateTime ? $basket->get_validation_end_date()->format(DATE_ATOM) : null) , 'validation_end_date' => $expires_on_atom
, 'validation_infos' => $basket->get_validation_infos() , 'validation_infos' => $basket->getValidation()->getValidationString($user)
, 'validation_confirmed' => $basket->is_confirmed() , 'validation_confirmed' => $basket->getValidation()->getParticipant($user)->getIsConfirmed()
, 'mine' => $basket->is_mine() , 'mine' => $basket->getValidation()->isInitiator($user)
) )
, $ret , $ret
); );

View File

@@ -1,6 +1,6 @@
<?php <?php
require_once dirname(__FILE__) . "/../../../../lib/vendor/oauth2/lib/OAuth2.inc"; require_once __DIR__ . "/../../../../lib/vendor/oauth2/lib/OAuth2.inc";
/* /*
* This file is part of Phraseanet * This file is part of Phraseanet
* *

View File

@@ -9,11 +9,11 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
$new_include_path = dirname(__FILE__) . "/../../../../vendor/" . PATH_SEPARATOR . get_include_path(); $new_include_path = __DIR__ . "/../../../../vendor/" . PATH_SEPARATOR . get_include_path();
set_include_path($new_include_path); set_include_path($new_include_path);
require_once dirname(__FILE__) . "/../../../../vendor/Phlickr/Api.php"; require_once __DIR__ . "/../../../../vendor/Phlickr/Api.php";
require_once dirname(__FILE__) . "/../../../../vendor/Phlickr/Uploader.php"; require_once __DIR__ . "/../../../../vendor/Phlickr/Uploader.php";
/** /**
* *

View File

@@ -88,7 +88,7 @@ class Bridge_Api_Auth_OAuth2 extends Bridge_Api_Auth_Abstract implements Bridge_
$response = json_decode($response_json, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS); $response = json_decode($response_json, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS);
if (!is_array($response) || !isset($response['refresh_token']) || !isset($response['access_token'])) if (!is_array($response) || !isset($response['refresh_token']) || !isset($response['access_token']))
throw new Bridge_Exception_ApiConnectorAccessTokenFailed('Unable to retrive tokens'); throw new Bridge_Exception_ApiConnectorAccessTokenFailed('Unable to retrieve tokens');
return array('refresh_token' => $response['refresh_token'], 'auth_token' => $response['access_token']); return array('refresh_token' => $response['refresh_token'], 'auth_token' => $response['access_token']);
} }

View File

@@ -9,7 +9,7 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
require_once dirname(__FILE__) . "/../../../classes/DailymotionWithoutOauth2.php"; require_once __DIR__ . "/../../../classes/DailymotionWithoutOauth2.php";
use \Symfony\Component\HttpFoundation\Request; use \Symfony\Component\HttpFoundation\Request;

View File

@@ -9,13 +9,13 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
$new_include_path = dirname(__FILE__) . "/../../../vendor/" . PATH_SEPARATOR . get_include_path(); $new_include_path = __DIR__ . "/../../../vendor/" . PATH_SEPARATOR . get_include_path();
set_include_path($new_include_path); set_include_path($new_include_path);
use \Symfony\Component\HttpFoundation\Request; use \Symfony\Component\HttpFoundation\Request;
require_once dirname(__FILE__) . "/../../../vendor/Phlickr/Api.php"; require_once __DIR__ . "/../../../vendor/Phlickr/Api.php";
require_once dirname(__FILE__) . "/../../../vendor/Phlickr/Uploader.php"; require_once __DIR__ . "/../../../vendor/Phlickr/Uploader.php";
/** /**
* *

View File

@@ -9,7 +9,7 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
$new_include_path = dirname(__FILE__) . '/../../../vendor/gdata/' . PATH_SEPARATOR . get_include_path(); $new_include_path = __DIR__ . '/../../../vendor/gdata/' . PATH_SEPARATOR . get_include_path();
set_include_path($new_include_path); set_include_path($new_include_path);
require_once('Zend/Loader.php'); require_once('Zend/Loader.php');
@@ -245,7 +245,7 @@ class Bridge_Api_Youtube extends Bridge_Api_Abstract implements Bridge_Api_Inter
break; break;
default: default:
throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type); throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
break; break;
} }
} }

View File

@@ -15,7 +15,7 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Bridge_Exception extends Exception class Bridge_Exception extends \Exception
{ {
} }

View File

@@ -15,7 +15,7 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Bridge_Exception_ApiConnectorNotConfigured extends Bridge_Exception class Bridge_Exception_ApiConnectorNotConfigured extends \Bridge_Exception
{ {
} }

View File

@@ -15,7 +15,7 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class Bridge_Exception_ApiConnectorNotConnected extends Bridge_Exception class Bridge_Exception_ApiConnectorNotConnected extends \Bridge_Exception
{ {
} }

View File

@@ -25,6 +25,10 @@ abstract class Feed_Abstract
* *
*/ */
const FORMAT_ATOM = 'atom'; const FORMAT_ATOM = 'atom';
/**
*
*/
const FORMAT_COOLIRIS = 'cooliris';
/** /**
* *

View File

@@ -57,6 +57,8 @@ class Feed_Adapter extends Feed_Abstract implements Feed_Interface, cache_cachea
const CACHE_ENTRY_NUMBER = 'entrynumber'; const CACHE_ENTRY_NUMBER = 'entrynumber';
const CACHE_USER_TOKEN = 'usr_token'; const CACHE_USER_TOKEN = 'usr_token';
const MAX_ENTRIES = 20;
/** /**
* *
@@ -561,7 +563,7 @@ class Feed_Adapter extends Feed_Abstract implements Feed_Interface, cache_cachea
public function get_entries($offset_start, $how_many) public function get_entries($offset_start, $how_many)
{ {
$offset_start = (int) $offset_start; $offset_start = (int) $offset_start;
$how_many = $how_many > 20 ? 20 : (int) $how_many; $how_many = $how_many > self::MAX_ENTRIES ? self::MAX_ENTRIES : (int) $how_many;
$sql = 'SELECT id $sql = 'SELECT id
FROM feed_entries FROM feed_entries

View File

@@ -158,6 +158,16 @@ class Feed_Aggregate extends Feed_Abstract implements Feed_Interface
, 'application/atom+xml' , 'application/atom+xml'
); );
break; break;
case self::FORMAT_COOLIRIS:
return new Feed_Link(
sprintf('%sfeeds/cooliris/%s'
, $registry->get('GV_ServerName')
, ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
);
break;
default: default:
case self::FORMAT_RSS: case self::FORMAT_RSS:
return new Feed_Link( return new Feed_Link(

View File

@@ -0,0 +1,459 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package Feeds
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Feed_XML_Cooliris extends Feed_XML_Abstract implements Feed_XML_Interface
{
/**
* RSS version
*/
const VERSION = '2.0';
/**
*
* @var Array
*/
protected $required_fields = array('title', 'subtitle', 'link');
/**
*
* @var string
*/
protected $language;
/**
*
* @var string
*/
protected $copyright;
/**
*
* @var string
*/
protected $managingEditor;
/**
*
* @var string
*/
protected $webMaster;
/**
*
* @var DateTime
*/
protected $lastBuildDate;
/**
*
* @var string
*/
protected $categories;
/**
*
* @var string
*/
protected $docs = 'http://blogs.law.harvard.edu/tech/rss';
/**
*
* @var int
*/
protected $ttl;
/**
*
* @var Feed_XML_RSS_Image
*/
protected $image;
/**
*
* @var string
*/
protected $skipHours = array();
/**
*
* @var string
*/
protected $skipDays = array();
/**
*
* @var string
*/
protected $mimetype = 'application/rss+xml';
/**
*
* @param string $language
* @return Feed_XML_RSS
*/
public function set_language($language)
{
$this->language = $language;
return $this;
}
/**
*
* @param string $language
* @return Feed_XML_RSS
*/
public function set_copyright($copyright)
{
$this->copyright = $copyright;
return $this;
}
/**
*
* @param string $managingEditor
* @return Feed_XML_RSS
*/
public function set_managingEditor($managingEditor)
{
$this->managingEditor = $managingEditor;
return $this;
}
/**
*
* @param string $webMaster
* @return Feed_XML_RSS
*/
public function set_webMaster($webMaster)
{
$this->webMaster = $webMaster;
return $this;
}
/**
*
* @param DateTime $lastBuildDate
* @return Feed_XML_RSS
*/
public function set_lastBuildDate(DateTime $lastBuildDate)
{
$this->lastBuildDate = $lastBuildDate;
return $this;
}
/**
*
* @param string $category
* @return Feed_XML_RSS
*/
public function set_category($category)
{
$this->categories[] = $category;
return $this;
}
/**
*
* @param string $docs
* @return Feed_XML_RSS
*/
public function set_docs($docs)
{
$this->docs = $docs;
return $this;
}
/**
*
* @param int $ttl
* @return Feed_XML_RSS
*/
public function set_ttl($ttl)
{
$this->ttl = $ttl;
return $this;
}
/**
*
* @param Feed_XML_RSS_Image $image
* @return Feed_XML_RSS
*/
public function set_image(Feed_XML_RSS_Image $image)
{
$this->image = $image;
return $this;
}
/**
*
* @param string $skipHours
* @return Feed_XML_RSS
*/
public function set_skipHour($hour)
{
$this->skipHours[] = (int) $hour;
return $this;
}
/**
*
* @param string $skipDays
* @return Feed_XML_RSS
*/
public function set_skipDays($day)
{
$this->skipDays[] = $day;
return $this;
}
/**
*
* @return string
*/
public function render()
{
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->formatOutput = true;
$doc->standalone = true;
$root = $this->addTag($doc, $doc, 'rss');
$root->setAttribute('version', self::VERSION);
$root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
$root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
$root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
$channel = $this->addTag($doc, $root, 'channel');
$this->addTag($doc, $channel, 'title', $this->title);
$this->addTag($doc, $channel, 'dc:title', $this->title);
$this->addTag($doc, $channel, 'description', $this->subtitle);
if ($this->link instanceof Feed_Link)
$this->addTag($doc, $channel, 'link', $this->link->get_href());
if ($this->language)
$this->addTag($doc, $channel, 'language', $this->language);
if ($this->copyright)
$this->addTag($doc, $channel, 'copyright', $this->copyright);
if ($this->managingEditor)
$this->addTag($doc, $channel, 'managingEditor', $this->managingEditor);
if ($this->webMaster)
$this->addTag($doc, $channel, 'webMaster', $this->webMaster);
if ($this->updated_on instanceof DateTime)
{
$updated_on = $this->updated_on->format(DATE_RFC2822);
$this->addTag($doc, $channel, 'pubDate', $updated_on);
}
if ($this->lastBuildDate instanceof DateTime)
{
$last_build = $this->lastBuildDate->format(DATE_RFC2822);
$this->addTag($doc, $channel, 'lastBuildDate', $last_build);
}
if (count($this->categories) > 0)
{
foreach ($this->categories as $category)
{
$this->addTag($doc, $channel, 'category', $category);
}
}
if ($this->generator)
$this->addTag($doc, $channel, 'generator', $this->generator);
if ($this->docs)
$this->addTag($doc, $channel, 'docs', $this->docs);
if ($this->ttl)
$this->addTag($doc, $channel, 'ttl', $this->ttl);
if ($this->image instanceof Feed_XML_RSS_Image)
{
$image = $this->addTag($doc, $channel, 'image');
$this->addTag($doc, $image, 'url', $this->image->get_url());
$this->addTag($doc, $image, 'title', $this->image->get_title());
$this->addTag($doc, $image, 'link', $this->image->get_link());
if ($this->image->get_width())
$this->addTag($doc, $image, 'width', $this->image->get_width());
if ($this->image->get_height())
$this->addTag($doc, $image, 'height', $this->image->get_height());
if ($this->image->get_description())
$this->addTag($doc, $image, 'description', $this->image->get_description());
}
if (count($this->skipHours))
{
$skipHours = $this->addTag($doc, $channel, 'skipHours');
foreach ($this->skipHours as $hour)
{
$this->addTag($doc, $skipHours, 'hour', $hour);
}
}
if (count($this->skipDays) > 0)
{
$skipDays = $this->addTag($doc, $channel, 'skipDays');
foreach ($this->skipDays as $day)
{
$this->addTag($doc, $skipDays, 'day', $day);
}
}
if ($this->link instanceof Feed_Link)
{
$self_link = $this->addTag($doc, $channel, 'atom:link');
$self_link->setAttribute('rel', 'self');
$self_link->setAttribute('href', $this->link->get_href());
}
$this->add_navigation($doc, $channel, true);
foreach ($this->items as $item)
{
$this->add_item($doc, $channel, $item);
}
return $doc->saveXML();
}
/**
*
* @param DOMDocument $document
* @param DOMNode $node
* @param Feed_Entry_Adapter $entry
* @return DOMElement
*/
protected function add_item(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry)
{
foreach ($entry->get_content() as $content)
{
$this->addContent($document, $node, $entry, $content);
}
return;
}
/**
*
* @param DOMDocument $document
* @param DOMNode $item
* @param Feed_Entry_Item $content
* @return Feed_XML_Interface
*/
protected function addContent(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry, Feed_Entry_Item $content)
{
$preview_sd = $content->get_record()->get_subdef('preview');
$preview_permalink = $preview_sd->get_permalink();
$thumbnail_sd = $content->get_record()->get_thumbnail();
$thumbnail_permalink = $thumbnail_sd->get_permalink();
$medium = strtolower($content->get_record()->get_type());
if (!in_array($medium, array('image', 'audio', 'video')))
return $this;
if (!$preview_permalink || !$thumbnail_permalink)
return $this;
//add item node to channel node
$item = $this->addTag($document, $node, 'item');
$title_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Title);
if ($title_field)
{
$str_title = $title_field->get_value(true, ' ');
}
else
{
$str_title = $content->get_record()->get_title();
}
//attach tile node to item node
$title = $this->addTag($document, $item, 'title', $str_title);
$desc_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Description);
if ($desc_field)
{
$str_desc = $desc_field->get_value(true, ' ');
}
else
{
$str_desc = '';
}
//attach desc node to item node
$desc = $this->addTag($document, $item, 'description', $str_desc);
$duration = $content->get_record()->get_duration();
if ($preview_permalink)
{
$preview = $this->addTag($document, $item, 'media:content');
$preview->setAttribute('url', $preview_permalink->get_url());
$preview->setAttribute('fileSize', $preview_sd->get_size());
$preview->setAttribute('type', $preview_sd->get_mime());
$preview->setAttribute('medium', $medium);
$preview->setAttribute('expression', 'full');
$preview->setAttribute('isDefault', 'true');
if ($preview_sd->get_width())
$preview->setAttribute('width', $preview_sd->get_width());
if ($preview_sd->get_height())
$preview->setAttribute('height', $preview_sd->get_height());
if ($duration)
$preview->setAttribute('duration', $duration);
}
if ($thumbnail_permalink)
{
$thumbnail = $this->addTag($document, $item, 'media:thumbnail');
$thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
if ($thumbnail_sd->get_width())
$thumbnail->setAttribute('width', $thumbnail_sd->get_width());
if ($thumbnail_sd->get_height())
$thumbnail->setAttribute('height', $thumbnail_sd->get_height());
$thumbnail = $this->addTag($document, $item, 'media:content');
$thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
$thumbnail->setAttribute('fileSize', $thumbnail_sd->get_size());
$thumbnail->setAttribute('type', $thumbnail_sd->get_mime());
$thumbnail->setAttribute('medium', $medium);
$thumbnail->setAttribute('isDefault', 'false');
if ($thumbnail_sd->get_width())
$thumbnail->setAttribute('width', $thumbnail_sd->get_width());
if ($thumbnail_sd->get_height())
$thumbnail->setAttribute('height', $thumbnail_sd->get_height());
if ($duration)
$thumbnail->setAttribute('duration', $duration);
}
return $this;
}
}

View File

@@ -0,0 +1,3 @@
<?php
require_once __DIR__ . '/../vendor/PHPShortener/phpshortener.class.php';

View File

@@ -88,8 +88,7 @@ class Session_Handler
if (!$this->is_authenticated()) if (!$this->is_authenticated())
return; return;
$user = User_Adapter::getInstance($this->get_usr_id(), $this->appbox);
$user->ACL()->delete_injected_rights();
$this->storage()->reset(); $this->storage()->reset();
$this->close_phrasea_session(); $this->close_phrasea_session();
@@ -568,10 +567,12 @@ class Session_Handler
return $this; return $this;
} }
$registry = $this->appbox->get_registry(); $Core = bootstrap::getCore();
$registry = $Core->getRegistry();
$date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days'); $date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days');
$events_mngr = eventsmanager_broker::getInstance($this->appbox); $events_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
$sql = 'SELECT v.id as validate_id, v.usr_id, v.ssel_id $sql = 'SELECT v.id as validate_id, v.usr_id, v.ssel_id
, s.usr_id as owner, t.value , s.usr_id as owner, t.value

View File

@@ -179,7 +179,7 @@ class Setup_Upgrade
*/ */
public static function get_lock_file() public static function get_lock_file()
{ {
return dirname(__FILE__) . '/../../../tmp/upgrade.lock'; return __DIR__ . '/../../../tmp/upgrade.lock';
} }
/** /**

View File

@@ -894,6 +894,11 @@ class User_Adapter implements User_Interface, cache_cacheableInterface
return $this->is_template; return $this->is_template;
} }
public function get_template_owner()
{
return $this->template_owner;
}
public static function get_usr_id_from_email($email) public static function get_usr_id_from_email($email)
{ {
if(is_null($email)) if(is_null($email))
@@ -1298,7 +1303,8 @@ class User_Adapter implements User_Interface, cache_cacheableInterface
protected function load_notifications_preferences() protected function load_notifications_preferences()
{ {
$evt_mngr = eventsmanager_broker::getInstance($this->appbox); $Core = bootstrap::getCore();
$evt_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
$notifications = $evt_mngr->list_notifications_available($this->id); $notifications = $evt_mngr->list_notifications_available($this->id);
foreach ($notifications as $notification_group => $nots) foreach ($notifications as $notification_group => $nots)
@@ -1401,7 +1407,7 @@ class User_Adapter implements User_Interface, cache_cacheableInterface
{ {
$lngs = array(); $lngs = array();
$path = dirname(__FILE__) . "/../../../locale"; $path = __DIR__ . "/../../../locale";
if ($hdir = opendir($path)) if ($hdir = opendir($path))
{ {
while (false !== ($file = readdir($hdir))) while (false !== ($file = readdir($hdir)))
@@ -1423,95 +1429,6 @@ class User_Adapter implements User_Interface, cache_cacheableInterface
return $lngs; return $lngs;
} }
public static function detectLanguage(registryInterface $registry, $setLng = null)
{
$avLanguages = self::avLanguages();
$sel = $askLng = $askLocale = '';
if ($setLng !== null)
{
$askLng = substr($setLng, 0, 2);
$askLocale = $setLng;
}
elseif (Session_Handler::isset_cookie('locale'))
{
$askLng = substr(Session_Handler::get_cookie('locale'), 0, 2);
$askLocale = Session_Handler::get_cookie('locale');
}
elseif (strlen($registry->get('GV_default_lng')) > 2)
{
$askLng = substr($registry->get('GV_default_lng'), 0, 2);
$askLocale = $registry->get('GV_default_lng');
}
if ($askLng != '' && isset($avLanguages[$askLng]) && isset($avLanguages[$askLng][$askLocale]))
{
$avLanguages[$askLng][$askLocale]['selected'] = true;
$sel = $askLocale;
}
if ($sel === '' && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
{
$languages = explode(';', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$found = false;
foreach ($languages as $language)
{
$language = explode(',', strtolower($language));
if (count($language) != 2)
continue;
foreach ($language as $lang)
{
if (strpos($lang, '-') == 2 && strlen($lang) == 5)
{
$l = explode('-', $lang);
$l[0] = strtolower($l[0]);
$l[1] = strtoupper($l[1]);
if ($sel != '')
{
$found = true;
break;
}
$lang = implode('_', $l);
if (isset($avLanguages[$l[0]]))
{
if (!isset($avLanguages[$l[0]][$lang]))
{
$lang = end(array_keys($avLanguages[$l[0]]));
}
$avLanguages[$l[0]][$lang]['selected'] = true;
$sel = $lang;
$found = true;
break;
}
}
}
if ($found)
break;
}
if (!$found && array_key_exists(substr($registry->get('GV_default_lng'), 0, 2), $avLanguages))
{
$avLanguages[substr($registry->get('GV_default_lng'), 0, 2)][$registry->get('GV_default_lng')]['selected'] = true;
$sel = $registry->get('GV_default_lng');
}
}
if ($sel == '')
{
$key = end(array_keys($avLanguages));
$lang = end(array_keys($avLanguages[$key]));
$avLanguages[$key][$lang]['selected'] = true;
$sel = $lang;
}
Session_Handler::set_locale($sel);
$sel = explode('_', $sel);
return $avLanguages;
}
public static function get_wrong_email_users(appbox $appbox) public static function get_wrong_email_users(appbox $appbox)
{ {

View File

@@ -147,8 +147,6 @@ interface User_Interface
public static function avLanguages(); public static function avLanguages();
public static function detectLanguage(registryInterface $registry, $setLng = null);
public function setPrefs($prop, $value); public function setPrefs($prop, $value);
public function getPrefs($prop); public function getPrefs($prop);

View File

@@ -88,6 +88,11 @@ class User_Query implements User_QueryInterface
* @var boolean * @var boolean
*/ */
protected $include_templates = false; protected $include_templates = false;
/**
*
* @var boolean
*/
protected $only_templates = false;
/** /**
* *
* @var Array * @var Array
@@ -123,10 +128,10 @@ class User_Query implements User_QueryInterface
const SORT_FIRSTNAME= 'usr_prenom'; const SORT_FIRSTNAME= 'usr_prenom';
const SORT_LASTNAME= 'usr_nom'; const SORT_LASTNAME= 'usr_nom';
const SORT_COMPANY = 'societe'; const SORT_COMPANY = 'societe';
const SORT_LOGIN = 'login'; const SORT_LOGIN = 'usr_login';
const SORT_EMAIL = 'usr_mail'; const SORT_EMAIL = 'usr_mail';
const SORT_ID = 'usr_id'; const SORT_ID = 'usr_id';
const SORT_CREATIONDATE = 'creationdate'; const SORT_CREATIONDATE = 'usr_creationdate';
const SORT_COUNTRY = 'pays'; const SORT_COUNTRY = 'pays';
const SORT_LASTMODEL = 'lastModel'; const SORT_LASTMODEL = 'lastModel';
@@ -191,18 +196,22 @@ class User_Query implements User_QueryInterface
$sql .= ' AND usr_login NOT LIKE "(#deleted_%" '; $sql .= ' AND usr_login NOT LIKE "(#deleted_%" ';
if ($this->include_invite) if (!$this->include_invite)
{ {
$sql .= ' AND usr.invite=0 '; $sql .= ' AND usr.invite=0 ';
} }
if ($this->include_templates === false) if ($this->only_templates === true)
{
$sql .= ' AND model_of = ' . $session->get_usr_id();
}
elseif ($this->include_templates === false)
{ {
$sql .= ' AND model_of=0'; $sql .= ' AND model_of=0';
} }
else else
{ {
$sql .= ' AND (model_of=0 OR model_of= ' . $session->get_usr_id() . ' ) '; $sql .= ' AND (model_of=0 OR model_of = ' . $session->get_usr_id() . ' ) ';
} }
$baslist = array(); $baslist = array();
@@ -355,6 +364,17 @@ class User_Query implements User_QueryInterface
return $this; return $this;
} }
/**
*
* @param boolean $boolean
* @return User_Query
*/
public function only_templates($boolean)
{
$this->only_templates = !!$boolean;
return $this;
}
/** /**
* *
@@ -390,6 +410,8 @@ class User_Query implements User_QueryInterface
case self::SORT_COMPANY: case self::SORT_COMPANY:
case self::SORT_LOGIN: case self::SORT_LOGIN:
case self::SORT_EMAIL: case self::SORT_EMAIL:
$sorter[$k] = ' usr.`' . $sort . '` COLLATE utf8_unicode_ci ';
break;
case self::SORT_ID: case self::SORT_ID:
case self::SORT_CREATIONDATE: case self::SORT_CREATIONDATE:
case self::SORT_COUNTRY: case self::SORT_COUNTRY:
@@ -410,7 +432,7 @@ class User_Query implements User_QueryInterface
$sorter[$k] .= ' ASC '; $sorter[$k] .= ' ASC ';
break; break;
case self::ORD_DESC: case self::ORD_DESC:
$sorter[$k] .= ' ASC '; $sorter[$k] .= ' DESC ';
break; break;
} }
} }

View File

@@ -74,7 +74,7 @@ class appbox extends base
$this->registry = $registry; $this->registry = $registry;
$this->session = Session_Handler::getInstance($this); $this->session = Session_Handler::getInstance($this);
require dirname(__FILE__) . '/../../config/connexion.inc'; require __DIR__ . '/../../config/connexion.inc';
$this->host = $hostname; $this->host = $hostname;
$this->port = $port; $this->port = $port;
@@ -371,15 +371,17 @@ class appbox extends base
protected function post_upgrade(Setup_Upgrade &$upgrader) protected function post_upgrade(Setup_Upgrade &$upgrader)
{ {
$Core = bootstrap::getCore();
$upgrader->add_steps(1 + count($this->get_databoxes())); $upgrader->add_steps(1 + count($this->get_databoxes()));
$this->apply_patches($this->get_version(), GV_version, true, $upgrader); $this->apply_patches($this->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
$this->setVersion(GV_version); $this->setVersion($Core->getVersion()->getNumber());
$upgrader->add_steps_complete(1); $upgrader->add_steps_complete(1);
foreach ($this->get_databoxes() as $databox) foreach ($this->get_databoxes() as $databox)
{ {
$databox->apply_patches($databox->get_version(), GV_version, true, $upgrader); $databox->apply_patches($databox->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
$databox->setVersion(GV_version); $databox->setVersion($Core->getVersion()->getNumber());
$upgrader->add_steps_complete(1); $upgrader->add_steps_complete(1);
} }
@@ -407,7 +409,7 @@ class appbox extends base
{ {
$credentials['dbname'] = $dbname; $credentials['dbname'] = $dbname;
} }
$connexion = dirname(__FILE__) . "/../../config/connexion.inc"; $connexion = __DIR__ . "/../../config/connexion.inc";
if (is_file($connexion)) if (is_file($connexion))
unlink($connexion); unlink($connexion);
@@ -420,7 +422,7 @@ class appbox extends base
} }
if (!file_put_contents($connexion, $connexionINI, FILE_APPEND) !== false) if (!file_put_contents($connexion, $connexionINI, FILE_APPEND) !== false)
throw new Exception(sprintf(_('Impossible d\'ecrire dans le dossier %s'), dirname(dirname(__FILE__)) . "/config/")); throw new Exception(sprintf(_('Impossible d\'ecrire dans le dossier %s'), dirname(__DIR__) . "/config/"));
if (function_exists('chmod')) if (function_exists('chmod'))
chmod($connexion, 0700); chmod($connexion, 0700);
@@ -543,7 +545,7 @@ class appbox extends base
public static function list_databox_templates() public static function list_databox_templates()
{ {
$files = array(); $files = array();
$dir = new DirectoryIterator(dirname(__FILE__) . '/../conf.d/data_templates/'); $dir = new DirectoryIterator(__DIR__ . '/../conf.d/data_templates/');
foreach ($dir as $fileinfo) foreach ($dir as $fileinfo)
{ {
if ($fileinfo->isFile()) if ($fileinfo->isFile())

View File

@@ -257,9 +257,10 @@ abstract class base implements cache_cacheableInterface
public function upgradeavailable() public function upgradeavailable()
{ {
$Core = bootstrap::getCore();
if ($this->get_version()) if ($this->get_version())
return version_compare(GV_version, $this->get_version(), '>'); return version_compare($Core->getVersion()->getNumber(), $this->get_version(), '>');
else else
return true; return true;
@@ -267,7 +268,7 @@ abstract class base implements cache_cacheableInterface
protected function upgradeDb($apply_patches, Setup_Upgrade &$upgrader) protected function upgradeDb($apply_patches, Setup_Upgrade &$upgrader)
{ {
require_once dirname(__FILE__) . '/../version.inc'; require_once __DIR__ . '/../version.inc';
$recommends = array(); $recommends = array();
@@ -338,10 +339,12 @@ abstract class base implements cache_cacheableInterface
} }
$current_version = $this->get_version(); $current_version = $this->get_version();
$Core = bootstrap::getCore();
$upgrader->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname())); $upgrader->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname()));
if ($apply_patches) if ($apply_patches)
{ {
$this->apply_patches($current_version, GV_version, false, $upgrader); $this->apply_patches($current_version, $Core->getVersion()->getNumber(), false, $upgrader);
} }
$upgrader->add_steps_complete(1); $upgrader->add_steps_complete(1);
@@ -390,7 +393,7 @@ abstract class base implements cache_cacheableInterface
return $this; return $this;
$structure = simplexml_load_file(dirname(__FILE__) . "/../../lib/conf.d/bases_structure.xml"); $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml");
if (!$structure) if (!$structure)
throw new Exception('Unable to load schema'); throw new Exception('Unable to load schema');
@@ -418,8 +421,8 @@ abstract class base implements cache_cacheableInterface
$this->createTable($table); $this->createTable($table);
} }
if (defined('GV_version')) $Core = bootstrap::getCore();
$this->setVersion(GV_version); $this->setVersion($Core->getVersion()->getNumber());
return $this; return $this;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,831 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @package Basket
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class basket_element_adapter implements cache_cacheableInterface
{
/**
*
* @var Array
*/
protected $choices;
/**
*
* @var boolean
*/
protected $is_validation_item = false;
/**
*
* @var int
*/
protected $validate_id;
/**
*
* @var int
*/
protected $my_agreement;
/**
*
* @var string
*/
protected $my_note;
/**
*
* @var int
*/
protected $avrAgree;
/**
*
* @var int
*/
protected $avrDisAgree;
/**
*
* @var int
*/
protected $sselcont_id;
/**
*
* @var int
*/
protected $parent_record_id;
/**
*
* @var int
*/
protected $ssel_id;
/**
*
* @var record_adapter
*/
protected $record;
protected $usr_id;
/**
*
* @var array
*/
protected static $_instance = array();
public function __construct($sselcont_id)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$this->usr_id = $session->get_usr_id();
$this->sselcont_id = (int) $sselcont_id;
$this->load();
return $this;
}
protected function load()
{
try
{
$datas = $this->get_data_from_cache();
$this->ssel_id = $datas['ssel_id'];
$this->order = $datas['order'];
$this->record = new record_adapter($datas['sbas_id'], $datas['record_id'], $this->order);
$this->avrDisAgree = $datas['avrDisAgree'];
$this->avrAgree = $datas['avrAgree'];
$this->is_validation_item = $datas['is_validation_item'];
$this->my_agreement = $datas['my_agreement'];
$this->my_note = $datas['my_note'];
$this->validate_id = $datas['validate_id'];
$this->choices = $datas['choices'];
$this->avrAgree = $datas['avrAgree'];
$this->avrDisAgree = $datas['avrDisAgree'];
return $this;
}
catch (Exception $e)
{
}
$sql = 'SELECT s.usr_id as owner, v.id as validate_id, v.can_see_others,
c.base_id, c.record_id, c.ord, c.ssel_id, v.usr_id,
d.agreement, d.note, d.updated_on
FROM (sselcont c, ssel s)
LEFT JOIN (validate v, validate_datas d)
ON (d.sselcont_id = c.sselcont_id AND d.validate_id = v.id )
WHERE s.ssel_id = c.ssel_id
AND c.sselcont_id = :sselcont_id';
try
{
$conn = connection::getPDOConnection();
$stmt = $conn->prepare($sql);
$stmt->execute(array(':sselcont_id' => $this->sselcont_id));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
}
catch (Exception $e)
{
}
$first = true;
foreach ($rs as $row)
{
if ($row['validate_id'])
{
$this->is_validation_item = true;
if ($row['owner'] == $this->usr_id)
$see_others = true;
else
$see_others = ($row['can_see_others'] == '1');
if (!$see_others)
{
if ($row['usr_id'] != $this->usr_id)
continue;
}
}
if ($first)
{
$sbas_id = (int) phrasea::sbasFromBas($row['base_id']);
$record_id = (int) $row['record_id'];
$this->ssel_id = (int) $row['ssel_id'];
$this->order = $number = (int) $row['ord'];
$this->record = new record_adapter($sbas_id, $record_id, $number);
if ($this->is_validation_item)
{
$this->choices = array();
$this->avrAgree = 0;
$this->avrDisAgree = 0;
}
$first = false;
}
if ($this->is_validation_item)
{
if ($row['usr_id'] == $this->usr_id)
{
$this->my_agreement = (int) $row['agreement'];
$this->my_note = $row['note'];
$this->validate_id = (int) $row['validate_id'];
}
$this->choices[$row['usr_id']] = array(
'usr_id' => $row['usr_id'],
'usr_name' => User_Adapter::getInstance($row['usr_id'], appbox::get_instance())->get_display_name(),
'is_mine' => ($row['usr_id'] == $this->usr_id),
'agreement' => $row['agreement'],
'updated_on' => $row['updated_on'],
'note' => $row['note']
);
$this->avrAgree += $row["agreement"] > 0 ? 1 : 0;
$this->avrDisAgree += $row["agreement"] < 0 ? 1 : 0;
}
}
$datas = array(
'ssel_id' => $this->ssel_id
, 'sbas_id' => (int) $sbas_id
, 'record_id' => $record_id
, 'order' => $this->order
, 'is_validation_item' => $this->is_validation_item
, 'my_agreement' => $this->my_agreement
, 'my_note' => $this->my_note
, 'validate_id' => $this->validate_id
, 'choices' => $this->choices
, 'avrAgree' => $this->avrAgree
, 'avrDisAgree' => $this->avrDisAgree
);
$this->set_data_to_cache($datas);
return $this;
}
public function get_record()
{
return $this->record;
}
/**
*
* @return int
*/
public function get_order()
{
return $this->order;
}
/**
*
* @param int $number
* @return basket_element_adapter
*/
public function set_order($order)
{
$this->order = (int) $order;
return $this;
}
/**
* @return basket_element_adapter
*/
public static function getInstance($sselcont_id)
{
if (!isset(self::$_instance[$sselcont_id]))
{
self::$_instance[$sselcont_id] = new self($sselcont_id);
}
return array_key_exists($sselcont_id, self::$_instance) ? self::$_instance[$sselcont_id] : false;
}
/**
*
* @param basket_adapter $basket
* @param int $base_id
* @param int $record_id
* @param int $parent_record_id
* @param string $adjust_validation_datas
* @param boolean $fixing
* @return basket_element_adapter
*/
public static function create(basket_adapter $basket, $base_id, $record_id, $parent_record_id, $adjust_validation_datas, $fixing)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$sbas_id = phrasea::sbasFromBas($base_id);
$record = new record_adapter($sbas_id, $record_id);
$ssel_id = $basket->get_ssel_id();
if (!$user->ACL()->has_right_on_base($base_id, 'canputinalbum'))
throw new Exception('You do not have rights' .
' to use this document in basket.');
$exists = false;
$sql = 'SELECT sselcont_id FROM sselcont
WHERE ssel_id = :ssel_id AND base_id = :base_id AND record_id = :record_id ';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':ssel_id' => $basket->get_ssel_id()
, ':base_id' => $base_id
, ':record_id' => $record_id
);
$stmt->execute($params);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
{
return new self($row['sselcont_id']);
}
$connbas = connection::getPDOConnection($sbas_id);
if (!$sbas_id)
throw new Exception('Unknown database');
if ($parent_record_id && $fixing === false)
{
if (!$user->ACL()->has_right_on_base($base_id, 'canaddrecord'))
throw new Exception('You do not have the right');
if ($record->is_grouping())
throw new Exception('Can\'t add grouping to grouping');
$ord = 0;
$sql = "SELECT (max(ord)+1) as ord
FROM regroup WHERE rid_parent = :parent_record_id";
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':parent_record_id' => $parent_record_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
{
$ord = is_null($row["ord"]) ? 0 : $row["ord"];
}
else
{
$ord = 0;
}
$sql = 'INSERT INTO regroup (id, rid_parent, rid_child, dateadd, ord)
VALUES (null, :parent_record_id, :record_id, NOW(), :ord)';
$params = array(
':parent_record_id' => $parent_record_id
, ':record_id' => $record_id
, ':ord' => $ord
);
$stmt = $connbas->prepare($sql);
$stmt->execute($params);
$stmt->closeCursor();
$sql = 'UPDATE record SET moddate = NOW() WHERE record_id = :parent_record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':parent_record_id' => $parent_record_id));
$stmt->closeCursor();
}
$sql = 'SELECT max(ord) as ord FROM sselcont WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':ssel_id' => $basket->get_ssel_id()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
{
$ord = (int) $row['ord'] + 1;
}
else
{
$ord = 0;
}
$sql = ' INSERT INTO sselcont
(sselcont_id, ssel_id, base_id, record_id, ord)
VALUES (null, :ssel_id, :base_id, :record_id, :ord) ';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':ssel_id' => $basket->get_ssel_id()
, ':base_id' => $base_id
, ':record_id' => $record_id
, ':ord' => $ord
);
$stmt->execute($params);
$stmt->closeCursor();
$sselcont_id = $appbox->get_connection()->lastInsertId();
$ret['error'] = false;
$ret['datas'][] = $sselcont_id;
$sql = 'UPDATE ssel SET updater=NOW() WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':ssel_id' => $basket->get_ssel_id()));
$stmt->closeCursor();
if ($adjust_validation_datas == 'myvalid')
{
$sql = 'INSERT INTO validate_datas
(SELECT distinct null as id, id as validate_id
, :sselcont_id as sselcont_id
, null as updated_on, 0 as agreement, "" as note
FROM validate
WHERE ssel_id = :ssel_id)';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':sselcont_id' => $sselcont_id, ':ssel_id' => $basket->get_ssel_id()));
$stmt->closeCursor();
$sql = 'SELECT usr_id FROM validate WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':ssel_id' => $basket->get_ssel_id()));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row)
{
if ($session->get_usr_id() != $row['usr_id'])
{
$basket->set_unread($row['usr_id']);
}
}
}
if ($parent_record_id)
{
$sql = 'SELECT null as id, ssel_id, usr_id
FROM ssel
WHERE usr_id != :usr_id AND rid = :parent_record_id
AND sbas_id = :sbas_id AND temporaryType="1"';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':usr_id' => $session->get_usr_id()
, ':parent_record_id' => $parent_record_id
, ':sbas_id' => $sbas_id
);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row)
{
$sql = 'SELECT max(ord) as ord FROM sselcont WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':ssel_id' => $row['ssel_id']));
$row2 = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
{
$ord = (int) $row2['ord'] + 1;
}
else
{
$ord = 0;
}
$sqlUp = ' INSERT INTO sselcont
(sselcont_id, ssel_id, base_id, record_id,ord)
VALUES (null, :ssel_id, :base_id, :record_id, :ord) ';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':ssel_id' => $row['ssel_id']
, ':base_id' => $base_id
, ':record_id' => $record_id
, ':ord' => $ord
);
$stmt->execute($params);
$stmt->closeCursor();
$sql = 'UPDATE ssel SET updater=NOW() WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':ssel_id' => $row['ssel_id']));
$stmt->closeCursor();
try
{
$basket_to_clean = basket_adapter::getInstance($appbox, $row['ssel_id'], $user->get_id());
$basket_to_clean->set_unread($row['usr_id']);
}
catch (Exception $e)
{
}
}
}
$basket->delete_cache();
return new self($sselcont_id);
}
/**
*
* @param string $note
* @return boolean
*/
function set_note($note)
{
if (!$this->is_validation_item)
{
throw new Exception('Element ' . $this->sselcont_id . ' is not a validation item');
}
$note = strip_tags($note);
if (!$this->validate_id)
return false;
$appbox = appbox::get_instance();
$usr_id = $appbox->get_session()->get_usr_id();
$sql = 'UPDATE validate_datas SET note = :note
WHERE sselcont_id = :sselcont_id AND validate_id = :validate_id ';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':note' => $note
, ':sselcont_id' => $this->sselcont_id
, ':validate_id' => $this->validate_id
);
$stmt->execute($params);
$stmt->closeCursor();
$this->my_note = $note;
foreach ($this->choices as $key => $values)
{
if ($values['is_mine'])
{
$this->choices[$key]['note'] = $note;
break;
}
}
try
{
$basket = basket_adapter::getInstance($appbox, $this->ssel_id, $usr_id);
$basket->delete_cache();
}
catch (Exception $e)
{
}
return $this;
}
/**
*
* @return void
*/
function load_users_infos()
{
if (!$this->is_validation_item)
{
throw new Exception('Element is not a validation item');
return false;
}
foreach ($this->choices as $key => $value)
{
$this->choices[$key]['usr_display'] = User_Adapter::getInstance($value['usr_id'], appbox::get_instance())->get_display_name();
}
}
/**
*
* @return int
*/
function get_note_count()
{
if (!$this->is_validation_item)
{
throw new Exception('Element is not a validation item');
return false;
}
$n = 0;
foreach ($this->choices as $key => $value)
{
if (trim($value['note']) != '')
$n++;
}
return $n;
}
/**
*
* @param boolean $boolean
* @return string
*/
function set_agreement($boolean)
{
if (!$this->is_validation_item)
{
throw new Exception('not a validation item');
}
if (!$this->validate_id)
throw new Exception('not a validation item');
$appbox = appbox::get_instance();
$usr_id = $appbox->get_session()->get_usr_id();
$boolean = in_array($boolean, array('1', '-1')) ? $boolean : '0';
$sql = 'UPDATE validate_datas
SET agreement = :agreement
WHERE sselcont_id = :sselcont_id
AND validate_id = :validate_id';
$params = array(
':agreement' => $boolean
, ':sselcont_id' => $this->sselcont_id
, ':validate_id' => $this->validate_id
);
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute($params);
$stmt->closeCursor();
$this->delete_data_from_cache();
$basket = basket_adapter::getInstance($appbox, $this->ssel_id, $usr_id);
$basket->delete_cache();
return $this;
}
/**
*
* @return int
*/
public function get_sselcont_id()
{
return $this->sselcont_id;
}
/**
*
* @return boolean
*/
public function is_validation_item()
{
return $this->is_validation_item;
}
/**
*
* @return int
*/
public function get_my_agreement()
{
return $this->my_agreement;
}
/**
*
* @return string
*/
public function get_my_note()
{
return $this->my_note;
}
/**
*
* @return Array
*/
public function get_choices()
{
return $this->choices;
}
/**
*
* @return int
*/
public function get_ssel_id()
{
return $this->ssel_id;
}
public static function is_in_validation_session(record_Interface $record, User_Interface $user)
{
$conn = connection::getPDOConnection();
$sql = 'SELECT v.id FROM sselcont c, validate v
WHERE c.base_id = :base_id AND c.record_id = :record_id
AND v.usr_id = :usr_id AND c.ssel_id = v.ssel_id';
$params = array(
':base_id' => $record->get_base_id()
, ':record_id' => $record->get_record_id()
, ':usr_id' => $user->get_id()
);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return!!$row;
}
public static function has_been_received(record_Interface $record, User_Interface $user)
{
$conn = connection::getPDOConnection();
$sql = 'SELECT sselcont_id FROM sselcont c, ssel s
WHERE c.ssel_id=s.ssel_id AND c.record_id = :record_id
AND c.base_id = :base_id AND s.pushFrom > 0
AND s.usr_id = :usr_id';
$params = array(
':base_id' => $record->get_base_id()
, ':record_id' => $record->get_record_id()
, ':usr_id' => $user->get_id()
);
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return!!$row;
}
public function get_avrAgree()
{
return $this->avrAgree;
}
public function get_avrDisAgree()
{
return $this->avrDisAgree;
}
public function validate(user_adapter $from_user, User_Adapter $to_user, $validate_id, $can_hd)
{
$appbox = appbox::get_instance();
if ($can_hd)
$to_user->ACL()->grant_hd_on($this->get_record(), $from_user, 'validate');
else
$to_user->ACL()->grant_preview_on($this->get_record(), $from_user, 'validate');
$sql = 'REPLACE INTO validate_datas
(id, validate_id, sselcont_id, updated_on, agreement)
VALUES
(null, :validate_id, :sselcont_id, null, 0)';
$stmt = $appbox->get_connection()->prepare($sql);
$params = array(
':validate_id' => $validate_id
, ':sselcont_id' => $this->get_sselcont_id()
);
$stmt->execute($params);
$stmt->closeCursor();
if (!$this->is_validation_item)
{
$this->choices = array();
$this->avrAgree = 0;
$this->avrDisAgree = 0;
}
$this->is_validation_item = true;
$this->choices[$to_user->get_id()] = array(
'usr_id' => $to_user->get_id(),
'usr_name' => $to_user->get_display_name(),
'is_mine' => ($to_user->get_id() == $this->usr_id),
'agreement' => 0,
'updated_on' => new DateTime(),
'note' => ''
);
if ($to_user->get_id() == $this->usr_id)
{
$this->validate_id = (int) $validate_id;
}
$this->delete_data_from_cache();
return $this;
}
public function get_cache_key($option = null)
{
return 'basket_element_' . $this->usr_id . '_' . $this->sselcont_id . ($option ? '_' . $option : '');
;
}
public function get_data_from_cache($option = null)
{
$appbox = appbox::get_instance();
return $appbox->get_data_from_cache($this->get_cache_key($option));
}
public function set_data_to_cache($value, $option = null, $duration = 0)
{
$appbox = appbox::get_instance();
return $appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
}
public function delete_data_from_cache($option = null)
{
$appbox = appbox::get_instance();
return $appbox->delete_data_from_cache($this->get_cache_key($option));
}
}

View File

@@ -1,179 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2010 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class basketCollection
{
private $baskets = array();
/**
* @param string $order (optionnal name_asc or date_desc - defaut to name_asc)
* @param array $except (array of element not return. available values are regroup baskets and recept)
* @return basketCollectionObject
*/
function __construct(appbox $appbox, $usr_id, $order='name asc', $except = array())
{
$user = User_Adapter::getInstance($usr_id, $appbox);
$current_timestamp_obj = new DateTime();
$current_timestamp = $current_timestamp_obj->format('U');
$sql = 'SELECT ssel_id FROM ssel WHERE usr_id = :usr_id
AND temporaryType="0"';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':usr_id' => $usr_id));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (count($rs) === 0)
{
$basket = basket_adapter::create($appbox, '', $user);
}
$baskets = array();
$baskets['baskets'] = $baskets['recept'] = $baskets['regroup'] = array();
$core = bootstrap::getCore();
$em = $core->getEntityManager();
$baskets['baskets'] = $em->getRepository('Entities\Basket')
->findBy(array('usr_id' => $usr_id, 'pusher_id' => null));
$baskets['regroup'] = $em->getRepository('Entities\StoryWZ')
->findBy(array('usr_id' => $usr_id));
// $sql = 'SELECT s.ssel_id, s.usr_id as owner, v.id as validate_id,
// s.temporaryType, s.pushFrom, v.expires_on FROM ssel s
// LEFT JOIN validate v
// ON (v.ssel_id = s.ssel_id AND v.usr_id = :usr_id_v)
// WHERE (s.usr_id = :usr_id_o OR v.id IS NOT NULL)';
//
// $stmt = $appbox->get_connection()->prepare($sql);
// $stmt->execute(array(':usr_id_o' => $usr_id, ':usr_id_v' => $usr_id));
// $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
// $stmt->closeCursor();
// foreach ($rs as $row)
// {
// $is_mine = ($row['owner'] == $usr_id);
//
// $expires_on_obj = new DateTime($row['expires_on']);
// $expires_on = $expires_on_obj->format('U');
//
// if ($row['validate_id'] != null && !$is_mine && $expires_on < $current_timestamp)
// continue;
//
// if ($row['temporaryType'] == '1')
// $baskets['regroup'][] = basket_adapter::getInstance($appbox, $row['ssel_id'], $usr_id);
// elseif (!is_null($row['validate_id']))
// {
//// $baskets['baskets'][] = basket_adapter::getInstance($appbox, $row['ssel_id'], $usr_id);
// }
// elseif ((int) $row['pushFrom'] > 0)
// $baskets['recept'][] = basket_adapter::getInstance($appbox, $row['ssel_id'], $usr_id);
//// else
//// $baskets['baskets'][] = basket_adapter::getInstance($appbox, $row['ssel_id'], $usr_id);
// }
$to_remove = array_intersect(array('recept', 'regroup', 'baskets'), $except);
foreach ($to_remove as $type)
$baskets[$type] = array();
if ($order == 'name asc')
{
uasort($baskets['baskets'], array('basketCollection', 'story_name_sort'));
uasort($baskets['regroup'], array('basketCollection', 'story_name_sort'));
uasort($baskets['recept'], array('basketCollection', 'story_name_sort'));
}
if ($order == 'date desc')
{
uasort($baskets['baskets'], array('basketCollection', 'story_date_sort'));
uasort($baskets['regroup'], array('basketCollection', 'story_date_sort'));
uasort($baskets['recept'], array('basketCollection', 'story_date_sort'));
}
$this->baskets = $baskets;
return $this;
}
public function get_baskets()
{
return $this->baskets;
}
function get_names()
{
$array_names = array();
foreach ($this->baskets as $type_name => $type)
{
foreach ($type as $basket)
{
$array_names[] = array('ssel_id' => $basket->get_ssel_id(), 'name' => $basket->get_name(), 'type' => $type_name);
}
}
return $array_names;
}
function story_date_sort($a, $b)
{
if (!$a->create || !$b->create)
return 0;
$comp = strcasecmp($a->create, $b->create);
if ($comp == 0)
return 0;
return $comp < 0 ? -1 : 1;
}
function story_name_sort($a, $b)
{
if (!$a->getName() || !$b->getName())
{
return 0;
}
$comp = strcasecmp($a->getName(), $b->getName());
if ($comp == 0)
return 0;
return $comp < 0 ? -1 : 1;
}
public static function get_updated_baskets()
{
$appbox = appbox::get_instance();
$conn = $appbox->get_connection();
$session = $appbox->get_session();
$sql = 'SELECT ssel_id FROM sselnew WHERE usr_id = :usr_id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':usr_id' => $session->get_usr_id()));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$baskets = array();
foreach ($rs as $row)
{
$baskets[] = basket_adapter::getInstance($appbox, $row['ssel_id'], $session->get_usr_id());
}
return $baskets;
}
}

View File

@@ -1,5 +1,5 @@
<?php <?php
require_once dirname(__FILE__) . '/../../../../vendor/moov/relocator.class.php'; require_once __DIR__ . '/../../../../vendor/moov/relocator.class.php';
/* /*
* This file is part of Phraseanet * This file is part of Phraseanet
* *

View File

@@ -32,14 +32,14 @@ class bootstrap
* *
* @return Alchemy\Phrasea\Core * @return Alchemy\Phrasea\Core
*/ */
public static function execute() public static function execute($env = 'main')
{ {
if(static::$core) if(static::$core)
{ {
return static::$core; return static::$core;
} }
static::$core = new Alchemy\Phrasea\Core(); static::$core = new Alchemy\Phrasea\Core($env);
return static::$core; return static::$core;
} }

View File

@@ -206,6 +206,9 @@ class caption_field implements cache_cacheableInterface
*/ */
protected static function serialize_value(Array $value, $separator) protected static function serialize_value(Array $value, $separator)
{ {
if(strlen($separator) > 1)
$separator = $separator[0];
if (trim($separator) === '') if (trim($separator) === '')
$separator = ' '; $separator = ' ';
else else
@@ -346,9 +349,9 @@ class caption_field implements cache_cacheableInterface
if ($this->databox_field->is_multi() === true) if ($this->databox_field->is_multi() === true)
{ {
if ($as_string === true && $custom_separator === false) if ($as_string === true && $custom_separator === false)
{
return $this->value; return $this->value;
}
$separator = $this->databox_field->get_separator(); $separator = $this->databox_field->get_separator();
$array_values = self::get_multi_values($this->value, $separator); $array_values = self::get_multi_values($this->value, $separator);

View File

@@ -59,8 +59,7 @@ class caption_record implements caption_interface, cache_cacheableInterface
protected function retrieve_fields() protected function retrieve_fields()
{ {
if(is_array($this->fields)) if (is_array($this->fields))
return $this->fields; return $this->fields;
$fields = array(); $fields = array();
@@ -97,7 +96,7 @@ class caption_record implements caption_interface, cache_cacheableInterface
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
} }
$this->fields = $rec_fields; $this->fields = $rec_fields;
@@ -134,7 +133,6 @@ class caption_record implements caption_interface, cache_cacheableInterface
{ {
$fields = $this->retrieve_fields(); $fields = $this->retrieve_fields();
if (isset($this->dces_elements[$label])) if (isset($this->dces_elements[$label]))
return $fields[$this->dces_elements[$label]]; return $fields[$this->dces_elements[$label]];
return null; return null;
} }
@@ -172,7 +170,10 @@ class caption_record implements caption_interface, cache_cacheableInterface
, $field->highlight_thesaurus() , $field->highlight_thesaurus()
); );
$fields[$field->get_name()] = $value; $fields[$field->get_name()] = array(
'value' => $value
, 'separator' => $field->get_databox_field()->get_separator()
);
} }
if ($searchEngine instanceof searchEngine_adapter) if ($searchEngine instanceof searchEngine_adapter)
@@ -185,7 +186,7 @@ class caption_record implements caption_interface, cache_cacheableInterface
foreach ($fields as $key => $value) foreach ($fields as $key => $value)
{ {
$fields[$key] = $ret[$n]; $fields[$key]['value'] = $ret[$n];
$n++; $n++;
} }
} }

View File

@@ -134,9 +134,9 @@ class connection
} }
else else
{ {
if (!is_file(dirname(__FILE__) . '/../../config/connexion.inc')) if (!is_file(__DIR__ . '/../../config/connexion.inc'))
throw new Exception('Unable to load config file'); throw new Exception('Unable to load config file');
require (dirname(__FILE__) . '/../../config/connexion.inc'); require (__DIR__ . '/../../config/connexion.inc');
} }
if (isset($connection_params[$name])) if (isset($connection_params[$name]))
{ {

View File

@@ -88,7 +88,7 @@ class connection_pdo extends connection_abstract implements connection_interface
*/ */
protected function log($message) protected function log($message)
{ {
file_put_contents(dirname(__FILE__) . '/../../../logs/sql_log.log', $message . "\n", FILE_APPEND); file_put_contents(__DIR__ . '/../../../logs/sql_log.log', $message . "\n", FILE_APPEND);
return $this; return $this;
} }

View File

@@ -142,7 +142,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
} }
@@ -157,7 +157,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
$conn = connection::getPDOConnection(); $conn = connection::getPDOConnection();
@@ -277,6 +277,7 @@ class databox extends base
SUM(1) AS n, SUM(size) AS siz FROM (record, subdef) SUM(1) AS n, SUM(size) AS siz FROM (record, subdef)
LEFT JOIN coll ON record.coll_id=coll.coll_id LEFT JOIN coll ON record.coll_id=coll.coll_id
WHERE record.record_id = subdef.record_id WHERE record.record_id = subdef.record_id
GROUP BY record.coll_id, name
UNION UNION
SELECT coll.coll_id, 0, asciiname, '_' AS name, 0 AS n, 0 AS siz SELECT coll.coll_id, 0, asciiname, '_' AS name, 0 AS n, 0 AS siz
FROM coll LEFT JOIN record ON record.coll_id=coll.coll_id FROM coll LEFT JOIN record ON record.coll_id=coll.coll_id
@@ -450,7 +451,6 @@ class databox extends base
$stmt->closeCursor(); $stmt->closeCursor();
if ($row) if ($row)
return self::get_instance((int) $row['sbas_id']); return self::get_instance((int) $row['sbas_id']);
try try
@@ -463,7 +463,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
$sql = 'USE `' . $dbname . '`'; $sql = 'USE `' . $dbname . '`';
@@ -575,7 +575,6 @@ class databox extends base
public function get_meta_structure() public function get_meta_structure()
{ {
if ($this->meta_struct) if ($this->meta_struct)
return $this->meta_struct; return $this->meta_struct;
try try
@@ -698,7 +697,6 @@ class databox extends base
} }
} }
if ($n > $limit) if ($n > $limit)
return true; return true;
return false; return false;
@@ -725,7 +723,7 @@ class databox extends base
public static function get_available_metadatas() public static function get_available_metadatas()
{ {
$available_fields = array(); $available_fields = array();
$dir = dirname(__FILE__) . '/metadata/description/'; $dir = __DIR__ . '/metadata/description/';
$registry = registry::get_instance(); $registry = registry::get_instance();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file)
{ {
@@ -960,15 +958,24 @@ class databox extends base
$this->saveStructure($dom_struct); $this->saveStructure($dom_struct);
$type = isset($field['type']) ? $field['type'] : 'string'; $type = isset($field['type']) ? $field['type'] : 'string';
$type = in_array($type, array(databox_field::TYPE_DATE, databox_field::TYPE_NUMBER, databox_field::TYPE_TEXT)) ? $type : databox_field::TYPE_TEXT; $type = in_array($type
, array(
databox_field::TYPE_DATE
, databox_field::TYPE_NUMBER
, databox_field::TYPE_STRING
, databox_field::TYPE_TEXT
)
) ? $type : databox_field::TYPE_STRING;
$meta_struct_field = databox_field::create($this, $fname); $meta_struct_field = databox_field::create($this, $fname);
$meta_struct_field $meta_struct_field
->set_readonly(isset($field['readonly']) ? $field['readonly'] : 0) ->set_readonly(isset($field['readonly']) ? $field['readonly'] : 0)
->set_indexable(isset($field['index']) ? $field['index'] : '1') ->set_indexable(isset($field['index']) ? $field['index'] : '1')
->set_separator(isset($field['separator']) ? $field['separator'] : '')
->set_required((isset($field['required']) && $field['required'] == 1))
->set_type($type) ->set_type($type)
->set_tbranch(isset($field['tbranch']) ? $field['tbranch'] : '') ->set_tbranch(isset($field['tbranch']) ? $field['tbranch'] : '')
->set_thumbtitle(isset($field['thumbtitle']) ? $field['thumbtitle'] : '0') ->set_thumbtitle(isset($field['thumbtitle']) ? $field['thumbtitle'] : (isset($field['thumbTitle']) ? $field['thumbTitle'] : '0'))
->set_multi(isset($field['multi']) ? $field['multi'] : 0) ->set_multi(isset($field['multi']) ? $field['multi'] : 0)
->set_report(isset($field['report']) ? $field['report'] : '1') ->set_report(isset($field['report']) ? $field['report'] : '1')
->save(); ->save();
@@ -979,7 +986,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
if (isset($field['regname'])) if (isset($field['regname']))
@@ -1213,7 +1220,6 @@ class databox extends base
public function get_structure() public function get_structure()
{ {
if ($this->structure) if ($this->structure)
return $this->structure; return $this->structure;
$this->structure = $this->retrieve_structure(); $this->structure = $this->retrieve_structure();
@@ -1228,7 +1234,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
$structure = null; $structure = null;
@@ -1254,7 +1260,6 @@ class databox extends base
public function get_cterms() public function get_cterms()
{ {
if ($this->cterms) if ($this->cterms)
return $this->cterms; return $this->cterms;
$sql = "SELECT value FROM pref WHERE prop='cterms'"; $sql = "SELECT value FROM pref WHERE prop='cterms'";
@@ -1421,7 +1426,6 @@ class databox extends base
public function get_cgus() public function get_cgus()
{ {
if ($this->cgus) if ($this->cgus)
return $this->cgus; return $this->cgus;
$this->load_cgus(); $this->load_cgus();
@@ -1439,7 +1443,7 @@ class databox extends base
} }
catch (Exception $e) catch (Exception $e)
{ {
} }
$sql = 'SELECT value, locale, updated_on FROM pref WHERE prop ="ToU"'; $sql = 'SELECT value, locale, updated_on FROM pref WHERE prop ="ToU"';

View File

@@ -124,6 +124,7 @@ class databox_field implements cache_cacheableInterface
const TYPE_TEXT = "text"; const TYPE_TEXT = "text";
const TYPE_DATE = "date"; const TYPE_DATE = "date";
const TYPE_STRING = "string";
const TYPE_NUMBER = "number"; const TYPE_NUMBER = "number";
/** /**
@@ -176,7 +177,7 @@ class databox_field implements cache_cacheableInterface
$this->required = !!$row['required']; $this->required = !!$row['required'];
$this->multi = !!$row['multi']; $this->multi = !!$row['multi'];
$this->report = !!$row['report']; $this->report = !!$row['report'];
$this->type = $row['type']; $this->type = $row['type'] ?: self::TYPE_STRING;
$this->tbranch = $row['tbranch']; $this->tbranch = $row['tbranch'];
if ($row['dces_element']) if ($row['dces_element'])
{ {
@@ -551,6 +552,9 @@ class databox_field implements cache_cacheableInterface
*/ */
public function set_separator($separator) public function set_separator($separator)
{ {
if (strpos($separator, ';') === false)
$separator .= ';';
$this->separator = $separator; $this->separator = $separator;
return $this; return $this;

View File

@@ -17,13 +17,16 @@
*/ */
function deleteRecord($lst, $del_children) function deleteRecord($lst, $del_children)
{ {
$Core = bootstrap::getCore();
$em = $Core->getEntityManager();
$BE_repository = $em->getRepository('\Entities\BasketElement');
$appbox = appbox::get_instance(); $appbox = appbox::get_instance();
$session = $appbox->get_session(); $session = $appbox->get_session();
$registry = $appbox->get_registry(); $registry = $Core->getRegistry();
$usr_id = $session->get_usr_id(); $user = $Core->getAuthenticatedUser();
$ACL = $user->ACL();
$ACL = User_Adapter::getInstance($usr_id, $appbox)->ACL();
$lst = explode(";", $lst); $lst = explode(";", $lst);
@@ -103,84 +106,14 @@ function deleteRecord($lst, $del_children)
} }
} }
$sql = array(); $basket_elements = $BE_repository->findElementsByRecord($record);
$params = array();
$n = 0; foreach($basket_elements as $basket_element)
foreach ($ret as $key=>$basrec)
{ {
$br = explode('_', $basrec); $em->remove($basket_element);
$sql[] = '(base_id = :base_id' . $n . ' AND record_id = :record_id' . $n . ')';
$params[':base_id' . $n] = $br[2];
$params[':record_id' . $n] = $br[1];
$sql_ssel = 'SELECT ssel_id, usr_id FROM ssel
WHERE sbas_id = :sbas_id AND rid = :record_id';
$stmt = $conn->prepare($sql_ssel);
$stmt->execute(array(':sbas_id' => $br[0], ':record_id' => $br[1]));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row)
{
try
{
$basket = basket_adapter::getInstance($appbox, $row['ssel_id'], $row['usr_id']);
$basket->delete_cache();
unset($basket);
}
catch (Exception $e)
{
}
}
$sql_ssel = 'DELETE FROM ssel WHERE sbas_id = :sbas_id AND rid = :record_id';
$stmt = $conn->prepare($sql_ssel);
$stmt->execute(array(':sbas_id' => $br[0], ':record_id' => $br[1]));
$stmt->closeCursor();
unset($br[2]);
$ret[$key] = implode('_', $br);
$n++;
} }
$em->flush();
if (count($sql) > 0)
{
$sql_res = 'SELECT DISTINCT ssel.usr_id, ssel.ssel_id FROM sselcont ,ssel
WHERE (' . implode(' OR ', $sql) . ')
AND sselcont.ssel_id = ssel.ssel_id AND ssel.usr_id = :usr_id';
$params[':usr_id'] = $usr_id;
$stmt = $conn->prepare($sql_res);
$stmt->execute($params);
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row)
{
try
{
$basket = basket_adapter::getInstance($appbox, $row['ssel_id'], $usr_id);
$basket->delete_cache();
}
catch (Exception $e)
{
}
}
$sql = 'DELETE FROM sselcont WHERE (' . implode(' OR ', $sql) . ')
AND ssel_id IN (SELECT ssel_id FROM ssel WHERE usr_id = :usr_id)';
$stmt = $conn->prepare($sql_res);
$stmt->execute($params);
$stmt->closeCursor();
}
return p4string::jsonencode($ret); return p4string::jsonencode($ret);
} }

View File

@@ -1486,6 +1486,7 @@ function getUsrInfos($usr, $arrayUsrs)
function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse) function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
{ {
$Core = bootstrap::getCore();
$appbox = appbox::get_instance(); $appbox = appbox::get_instance();
$session = $appbox->get_session(); $session = $appbox->get_session();
$registry = $appbox->get_registry(); $registry = $appbox->get_registry();
@@ -1507,6 +1508,8 @@ function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
$reading_confirm_to = $me->get_email(); $reading_confirm_to = $me->get_email();
} }
$em = $Core->getEntityManager();
foreach ($users as $oneuser => $rights) foreach ($users as $oneuser => $rights)
{ {
$new_basket = null; $new_basket = null;
@@ -1516,20 +1519,40 @@ function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
$user = User_Adapter::getInstance($oneuser, $appbox); $user = User_Adapter::getInstance($oneuser, $appbox);
$pusher = User_Adapter::getInstance($usr, $appbox); $pusher = User_Adapter::getInstance($usr, $appbox);
$new_basket = basket_adapter::create($appbox, $newBask, $user, '', $pusher); $new_basket = new \Entities\Basket();
$new_basket->set_unread(); $new_basket->setName($newBask);
$new_basket->setIsRead(false);
$new_basket->setPusher($pusher);
$new_basket->setOwner($user);
$em->persist($new_basket);
$nbchu++; $nbchu++;
$new_basket->push_list($parmLST, false); foreach($parmLST as $basrec)
{
$basrec = explode('_', $basrec);
$record = new record_adapter($basrec[0], $basrec[1]);
$BasketElement = new Entities\BasketElement();
$BasketElement->setRecord($record);
$BasketElement->setBasket($new_basket);
$em->persist($BasketElement);
$new_basket->addBasketElement($BasketElement);
}
$em->flush();
$finalUsers[] = $user->get_id(); $finalUsers[] = $user->get_id();
$canSendHD = sendHdOk($usr, $parmLST); $canSendHD = sendHdOk($usr, $parmLST);
foreach ($new_basket->get_elements() as $element) foreach ($new_basket->getElements() as $element)
{ {
$record = $element->get_record(); $record = $element->getRecord();
if ($rights['canHD'] && in_array($record->get_base_id(), $canSendHD)) if ($rights['canHD'] && in_array($record->get_base_id(), $canSendHD))
$user->ACL()->grant_hd_on($record, $me, 'push'); $user->ACL()->grant_hd_on($record, $me, 'push');
else else
@@ -1541,7 +1564,7 @@ function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
$from = trim($me->get_email()) != "" ? $me->get_email() : false; $from = trim($me->get_email()) != "" ? $me->get_email() : false;
$url = $registry->get('GV_ServerName') . 'lightbox/index.php?LOG=' . random::getUrlToken('view', $user->get_id(), null, $new_basket->get_ssel_id()); $url = $registry->get('GV_ServerName') . 'lightbox/index.php?LOG=' . random::getUrlToken('view', $user->get_id(), null, $new_basket->getId());
if ($me->get_id() == $user->get_id()) if ($me->get_id() == $user->get_id())
$my_link = $url; $my_link = $url;
@@ -1557,11 +1580,11 @@ function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
, 'url' => $url , 'url' => $url
, 'accuse' => $reading_confirm_to , 'accuse' => $reading_confirm_to
, 'message' => $mail_content , 'message' => $mail_content
, 'ssel_id' => $new_basket->get_ssel_id() , 'ssel_id' => $new_basket->getId()
); );
$evt_mngr = eventsmanager_broker::getInstance($appbox); $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core);
$evt_mngr->trigger('__PUSH_DATAS__', $params); $evt_mngr->trigger('__PUSH_DATAS__', $params);
} }
catch (Exception $e) catch (Exception $e)
@@ -1575,6 +1598,7 @@ function pushIt($usr, $newBask, $parmLST, $users, $mail_content, $lng, $accuse)
function pushValidation($usr, $ssel_id, $listUsrs, $time, $mail_content, $accuse) function pushValidation($usr, $ssel_id, $listUsrs, $time, $mail_content, $accuse)
{ {
$Core = bootstrap::getCore();
$appbox = appbox::get_instance(); $appbox = appbox::get_instance();
$session = $appbox->get_session(); $session = $appbox->get_session();
$registry = $appbox->get_registry(); $registry = $appbox->get_registry();
@@ -1605,10 +1629,16 @@ function pushValidation($usr, $ssel_id, $listUsrs, $time, $mail_content, $accuse
$expires = null; $expires = null;
} }
$em = $Core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
$basket = $repository->findUserBasket($ssel_id, $Core->getAuthenticatedUser());
$basket->setIsRead(false);
$basket = basket_adapter::getInstance($appbox, $ssel_id, $session->get_usr_id());
$basket->set_unread(); $em->merge($basket);
$em->flush();
foreach ($listUsrs as $oneuser => $rights) foreach ($listUsrs as $oneuser => $rights)
{ {
@@ -1637,7 +1667,7 @@ function pushValidation($usr, $ssel_id, $listUsrs, $time, $mail_content, $accuse
, 'accuse' => $reading_confirm_to , 'accuse' => $reading_confirm_to
); );
$evt_mngr = eventsmanager_broker::getInstance($appbox); $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core);
$evt_mngr->trigger('__PUSH_VALIDATION__', $params); $evt_mngr->trigger('__PUSH_VALIDATION__', $params);
if ($me->get_id() == $user->get_id()) if ($me->get_id() == $user->get_id())

View File

@@ -12,10 +12,16 @@ class eventsmanager_broker
* @var appbox * @var appbox
*/ */
protected $appbox; protected $appbox;
/**
*
* @var \Alchemy\Phrasea\Core
*/
protected $core;
private function __construct(appbox &$appbox) private function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core)
{ {
$this->appbox = $appbox; $this->appbox = $appbox;
$this->core = $core;
return $this; return $this;
} }
@@ -23,11 +29,11 @@ class eventsmanager_broker
/** /**
* @return eventsmanager * @return eventsmanager
*/ */
public static function getInstance(appbox &$appbox) public static function getInstance(appbox &$appbox, \Alchemy\Phrasea\Core $core)
{ {
if (!self::$_instance) if (!self::$_instance)
{ {
self::$_instance = new self($appbox); self::$_instance = new self($appbox, $core);
} }
return self::$_instance; return self::$_instance;
@@ -50,7 +56,7 @@ class eventsmanager_broker
{ {
continue; continue;
} }
$this->pool_classes[$classname] = new $classname($this->appbox, $this->appbox->get_registry(), $this); $this->pool_classes[$classname] = new $classname($this->appbox, $this->core, $this);
foreach ($this->pool_classes[$classname]->get_events() as $event) foreach ($this->pool_classes[$classname]->get_events() as $event)
$this->bind($event, $classname); $this->bind($event, $classname);
@@ -67,17 +73,17 @@ class eventsmanager_broker
{ {
$iterators_pool = array(); $iterators_pool = array();
$root = dirname(__FILE__) . '/../../'; $root = __DIR__ . '/../../';
if ($type == 'event') if ($type == 'event')
{ {
$iterators_pool['event'][] = new DirectoryIterator(dirname(__FILE__) . '/event/'); $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
if (file_exists(dirname(__FILE__) . '/event/')) if (file_exists(__DIR__ . '/event/'))
$iterators_pool['event'][] = new DirectoryIterator(dirname(__FILE__) . '/event/'); $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
} }
if ($type == 'notify') if ($type == 'notify')
{ {
$iterators_pool['notify'][] = new DirectoryIterator(dirname(__FILE__) . '/notify/'); $iterators_pool['notify'][] = new DirectoryIterator(__DIR__ . '/notify/');
} }
$ret = array(); $ret = array();
@@ -100,7 +106,7 @@ class eventsmanager_broker
{ {
continue; continue;
} }
$obj = new $classname($this->appbox, $this->appbox->get_registry(), $this); $obj = new $classname($this->appbox, $this->core, $this);
$ret[$classname] = $obj->get_name(); $ret[$classname] = $obj->get_name();
} }

View File

@@ -15,6 +15,11 @@ abstract class eventsmanager_eventAbstract
* @var registryInterface * @var registryInterface
*/ */
protected $registry; protected $registry;
/**
*
* @var \Alchemy\Phrasea\Core
*/
protected $core;
/** /**
* *
* @var eventsmanager * @var eventsmanager
@@ -22,10 +27,11 @@ abstract class eventsmanager_eventAbstract
protected $broker; protected $broker;
public function __construct(appbox &$appbox, registryInterface $registry, eventsmanager_broker &$broker) public function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{ {
$this->appbox = $appbox; $this->appbox = $appbox;
$this->registry = $registry; $this->registry = $core->getRegistry();
$this->core = $core;
$this->broker = $broker; $this->broker = $broker;
return $this; return $this;

View File

@@ -28,10 +28,10 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
* *
* @return notify_orderdeliver * @return notify_orderdeliver
*/ */
function __construct(appbox &$appbox, registryInterface &$registry, eventsmanager_broker &$broker) function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{ {
$this->group = _('Commande'); $this->group = _('Commande');
parent::__construct($appbox, $registry, $broker); parent::__construct($appbox, $core, $broker);
return $this; return $this;
} }
@@ -147,7 +147,10 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
try try
{ {
$basket = basket_adapter::getInstance($this->appbox, $ssel_id, $this->appbox->get_session()->get_usr_id()); $em = $this->core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
$basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser());
} }
catch (Exception $e) catch (Exception $e)
{ {
@@ -159,7 +162,7 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
$sender, $n, $sender, $n,
'<a href="/lightbox/compare/' '<a href="/lightbox/compare/'
. (string) $sx->ssel_id . '/" target="_blank">' . (string) $sx->ssel_id . '/" target="_blank">'
. $basket->get_name() . '</a>' . $basket->getName() . '</a>'
) )
, 'class' => '' , 'class' => ''
); );
@@ -196,7 +199,10 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
{ {
try try
{ {
$basket = basket_adapter::getInstance($this->appbox, $ssel_id, $this->appbox->get_session()->get_usr_id()); $em = $this->core->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
$basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser());
} }
catch (Exception $e) catch (Exception $e)
{ {
@@ -204,7 +210,7 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
} }
$subject = sprintf( $subject = sprintf(
_('push::mail:: Reception de votre commande %s'), _('push::mail:: Reception de votre commande %s'),
$basket->get_name() $basket->getName()
); );
$body = "<div>" $body = "<div>"

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