Merge with Scheduler 2 branch

This commit is contained in:
Romain Neutron
2012-03-19 19:14:10 +01:00
1801 changed files with 111300 additions and 157444 deletions

View File

@@ -1,37 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Silex\Application;
return call_user_func(
function()
{
$app = new Application();
$app->mount('/publications', new Controller_Admin_Publications());
$app->mount('/users', new Controller_Admin_Users());
$app->mount('/fields', new Controller_Admin_Fields());
$app->mount('/tests/connection', new Controller_Utils_ConnectionTest());
$app->mount('/tests/pathurl', new Controller_Utils_PathFileTest());
$app->error(function(\Exception $e)
{
return $e->getMessage();
});
return $app;
});

View File

@@ -1,457 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return call_user_func(
function()
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$app = new Silex\Application();
$app->get('/', function () use ($session, $appbox)
{
User_Adapter::updateClientInfos((6));
$basket_collection = new basketCollection($appbox, $session->get_usr_id());
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$browser = Browser::getInstance();
$template = 'lightbox/index.twig';
if (!$browser->isNewGeneration() && !$browser->isMobile())
$template = 'lightbox/IE6/index.twig';
$output = $twig->render($template, array(
'baskets_collection' => $basket_collection,
'module_name' => 'Lightbox',
'module' => 'lightbox'
)
);
$response = new Response($output);
$response->setCharset('UTF-8');
return $response;
}
);
$app->get('/ajax/NOTE_FORM/{sselcont_id}/', function($sselcont_id) use ($session, $appbox)
{
$browser = Browser::getInstance();
if (!$browser->isMobile())
return new Response('');
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$template = '/lightbox/note_form.twig';
$output = $twig->render($template, array('basket_element' => $basket_element, 'module_name' => ''));
return new Response($output);
}
)->assert('sselcont_id', '\d+');
$app->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function($sselcont_id)
{
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets'));
$browser = Browser::getInstance();
if ($browser->isMobile())
{
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$output = $twig->render('lightbox/basket_element.twig', array(
'basket_element' => $basket_element,
'module_name' => $basket_element->get_record()->get_title()
)
);
return new Response($output);
}
else
{
$template_options = 'lightbox/sc_options_box.twig';
$template_agreement = 'lightbox/agreement_box.twig';
$template_selector = 'lightbox/selector_box.twig';
$template_note = 'lightbox/sc_note.twig';
$template_preview = 'common/preview.html';
$template_caption = 'common/caption.html';
if (!$browser->isNewGeneration())
{
$template_options = 'lightbox/IE6/sc_options_box.twig';
$template_agreement = 'lightbox/IE6/agreement_box.twig';
}
$appbox = appbox::get_instance();
$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);
$ret = array();
$ret['number'] = $basket_element->get_record()->get_number();
$ret['title'] = $basket_element->get_record()->get_title();
$ret['preview'] = $twig->render($template_preview, array('record' => $basket_element->get_record(), 'not_wrapped' => true));
$ret['options_html'] = $twig->render($template_options, array('basket_element' => $basket_element));
$ret['agreement_html'] = $twig->render($template_agreement, array('basket' => $basket, 'basket_element' => $basket_element));
$ret['selector_html'] = $twig->render($template_selector, array('basket_element' => $basket_element));
$ret['note_html'] = $twig->render($template_note, array('basket_element' => $basket_element));
$ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $basket_element->get_record()));
$output = p4string::jsonencode($ret);
return new Response($output, 200, array('Content-Type' => 'application/json'));
}
}
)->assert('sselcont_id', '\d+');
$app->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function($entry_id, $item_id)
{
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br', 'formatoctet' => 'p4string::format_octets'));
$appbox = appbox::get_instance();
$entry = Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
$item = new Feed_Entry_Item($appbox, $entry, $item_id);
$browser = Browser::getInstance();
if ($browser->isMobile())
{
$output = $twig->render('lightbox/feed_element.twig', array(
'feed_element' => $item,
'module_name' => $item->get_record()->get_title()
)
);
return new Response($output);
}
else
{
$template_options = 'lightbox/sc_options_box.twig';
$template_preview = 'common/preview.html';
$template_caption = 'common/caption.html';
if (!$browser->isNewGeneration())
{
$template_options = 'lightbox/IE6/sc_options_box.twig';
}
$usr_id = $appbox->get_session()->get_usr_id();
$ret = array();
$ret['number'] = $item->get_record()->get_number();
$ret['title'] = $item->get_record()->get_title();
$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['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $item->get_record()));
$ret['agreement_html'] = $ret['selector_html'] = $ret['note_html'] = '';
$output = p4string::jsonencode($ret);
return new Response($output, 200, array('Content-type' => 'application/json'));
}
}
)->assert('entry_id', '\d+')->assert('item_id', '\d+');
$app->get('/validate/{ssel_id}/', function ($ssel_id) use ($session, $appbox)
{
User_Adapter::updateClientInfos((6));
$browser = Browser::getInstance();
$basket_collection = new basketCollection($appbox, $session->get_usr_id());
$basket = basket_adapter::getInstance($appbox, $ssel_id, $session->get_usr_id());
if ($basket->is_valid())
{
if($basket->get_first_element() instanceof basket_element_adapter)
$basket->get_first_element()->load_users_infos();
}
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$template = 'lightbox/validate.twig';
if (!$browser->isNewGeneration() && !$browser->isMobile())
$template = 'lightbox/IE6/validate.twig';
$response = new Response($twig->render($template, array(
'baskets_collection' => $basket_collection,
'basket' => $basket,
'local_title' => strip_tags($basket->get_name()),
'module' => 'lightbox',
'module_name' => _('admin::monitor: module validation')
)
));
$response->setCharset('UTF-8');
return $response;
}
)->assert('ssel_id', '\d+');
$app->get('/compare/{ssel_id}/', function ($ssel_id) use ($session, $appbox)
{
User_Adapter::updateClientInfos((6));
$browser = Browser::getInstance();
$basket_collection = new basketCollection($appbox, $session->get_usr_id());
$basket = basket_adapter::getInstance($appbox, $ssel_id, $session->get_usr_id());
if ($basket->is_valid())
{
$basket->get_first_element()->load_users_infos();
}
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$template = 'lightbox/validate.twig';
if (!$browser->isNewGeneration() && !$browser->isMobile())
$template = 'lightbox/IE6/validate.twig';
$response = new Response($twig->render($template, array(
'baskets_collection' => $basket_collection,
'basket' => $basket,
'local_title' => strip_tags($basket->get_name()),
'module' => 'lightbox',
'module_name' => _('admin::monitor: module validation')
)
));
$response->setCharset('UTF-8');
return $response;
}
)->assert('ssel_id', '\d+');
$app->get('/feeds/entry/{entry_id}/', function ($entry_id) use ($session, $appbox)
{
User_Adapter::updateClientInfos((6));
$browser = Browser::getInstance();
$feed_entry = Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$template = 'lightbox/feed.twig';
if (!$browser->isNewGeneration() && !$browser->isMobile())
$template = 'lightbox/IE6/feed.twig';
$output = $twig->render($template, array(
'feed_entry' => $feed_entry,
'first_item' => array_shift($feed_entry->get_content()),
'local_title' => $feed_entry->get_title(),
'module' => 'lightbox',
'module_name' => _('admin::monitor: module validation')
)
);
$response = new Response($output, 200);
$response->setCharset('UTF-8');
return $response;
}
)->assert('entry_id', '\d+');
$app->get('/ajax/LOAD_REPORT/{ssel_id}/', function($ssel_id) use ($appbox, $app)
{
$twig = new supertwig();
$twig->addFilter(array('nl2br' => 'nl2br'));
$browser = Browser::getInstance();
$template = 'lightbox/basket_content_report.twig';
$basket = basket_adapter::getInstance($appbox, $ssel_id, $appbox->get_session()->get_usr_id());
$response = new Response($twig->render($template, array('basket' => $basket)));
$response->setCharset('UTF-8');
return $response;
}
)->assert('ssel_id', '\d+');
$app->post('/ajax/SET_NOTE/{sselcont_id}/', function ($sselcont_id) use ($app)
{
$output = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees'));
try
{
$request = $app['request'];
$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)
{
return new Response('Bad Request : ' . $e->getMessage() . $e->getFile() . $e->getLine(), 400);
}
$output = p4string::jsonencode($output);
return new Response($output, 200, array('Content-Type' => 'application/json'));
}
)->assert('sselcont_id', '\d+');
$app->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function($sselcont_id) use ($app)
{
$request = $app['request'];
$agreement = (int) $request->get('agreement');
$ret = array(
'error' => true,
'releasable' => false,
'datas' => _('Erreur lors de la mise a jour des donnes ')
);
try
{
$appbox = appbox::get_instance();
$basket_element = basket_element_adapter::getInstance($sselcont_id);
$basket_element->set_agreement($agreement);
$basket = basket_adapter::getInstance($appbox, $basket_element->get_ssel_id(), $appbox->get_session()->get_usr_id());
$ret = array(
'error' => false
, 'datas' => ''
, 'releasable' => $basket->is_releasable() ? _('Do you want to send your report ?') : false
);
}
catch (Exception $e)
{
return new Response('Bad Request', 400);
}
$output = p4string::jsonencode($ret);
return new Response($output, 200, array('Content-Type' => 'application/json'));
}
)->assert('sselcont_id', '\d+');
$app->post('/ajax/SET_RELEASE/{ssel_id}/', function($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'));
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);
}
$output = p4string::jsonencode($datas);
$response = new Response($output, 200, array('Content-Type' => 'application/json'));
$response->setCharset('UTF-8');
return $response;
}
)->assert('ssel_id', '\d+');
$app->error(function($e)
{
$twig = new supertwig();
$registry = registry::get_instance();
$template = 'lightbox/error.twig';
if ($registry->get('GV_debug'))
{
$options = array(
'module' => 'validation',
'module_name' => _('admin::monitor: module validation'),
'error' => sprintf(
'%s in %s on line %s '
, $e->getMessage()
, $e->getFile()
, $e->getLine()
)
);
}
else
{
$options = array(
'module' => 'validation',
'module_name' => _('admin::monitor: module validation'),
'error' => ''
);
}
$output = $twig->render($template, $options);
$response = new Response($output, 404);
$response->setCharset('UTF-8');
return $response;
});
return $app;
}
);

View File

@@ -1,227 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return call_user_func(
function()
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$app = new Silex\Application();
$deliver_content = function(Session_Handler $session, record_adapter $record, $subdef, $watermark, $stamp, $app)
{
$file = $record->get_subdef($subdef);
if ($file->get_baseurl() !== '')
{
return $app->redirect($file->get_url());
}
$pathIn = $pathOut = $file->get_pathfile();
if ($watermark === true && $file->get_type() === media_subdef::TYPE_IMAGE)
{
$pathOut = recordutils_image::watermark($record->get_base_id(), $record->get_record_id());
}
elseif ($stamp === true && $file->get_type() === media_subdef::TYPE_IMAGE)
{
$pathOut = recordutils_image::stamp($record->get_base_id(), $record->get_record_id());
}
$log_id = null;
try
{
$registry = registry::get_instance();
$logger = $session->get_logger($record->get_databox());
$log_id = $logger->get_id();
$referrer = 'NO REFERRER';
if (isset($_SERVER['HTTP_REFERER']))
$referrer = $_SERVER['HTTP_REFERER'];
$record->log_view($log_id, $referrer, $registry->get('GV_sit'));
}
catch (Exception $e)
{
}
return set_export::stream_file($pathOut, $file->get_file(), $file->get_mime(), 'attachment');
};
$app->get('/datafiles/{sbas_id}/{record_id}/{subdef}/', function($sbas_id, $record_id, $subdef) use ($app, $session, $deliver_content)
{
$databox = databox::get_instance((int) $sbas_id);
$record = new record_adapter($sbas_id, $record_id);
$record->get_type();
if (!$session->is_authenticated())
throw new Exception_Session_NotAuthenticated();
$user = User_Adapter::getInstance($session->get_usr_id(), appbox::get_instance());
if (!$user->ACL()->has_access_to_subdef($record, $subdef))
throw new Exception_UnauthorizedAction();
$stamp = false;
$watermark = !$user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark)
{
$subdef_class = $databox
->get_subdef_structure()
->get_subdef($record->get_type(), $subdef)
->get_class();
if ($subdef_class == databox_subdefAbstract::CLASS_PREVIEW && $user->ACL()->has_preview_grant($record))
{
$watermark = false;
}
elseif ($subdef_class == databox_subdefAbstract::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record))
{
$watermark = false;
}
}
if ($watermark)
{
if (basket_element_adapter::is_in_validation_session($record, $user))
{
$watermark = false;
}
elseif (basket_element_adapter::has_been_received($record, $user))
{
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/view/'
, function($label, $sbas_id, $record_id, $key, $subdef)
{
$databox = databox::get_instance((int) $sbas_id);
$record = media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
if (!($record instanceof record_adapter))
throw new Exception('bad luck');
$twig = new supertwig();
$twig->addFilter(array('formatoctet' => 'p4string::format_octets'));
return $twig->render('overview.twig', array('subdef_name' => $subdef, 'module_name' => 'overview', 'module' => 'overview', 'view' => 'overview', 'record' => $record));
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/'
, function($label, $sbas_id, $record_id, $key, $subdef) use ($app, $session, $deliver_content)
{
$databox = databox::get_instance((int) $sbas_id);
$record = media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
if (!($record instanceof record_adapter))
throw new Exception('bad luck');
$watermark = $stamp = false;
if ($session->is_authenticated())
{
$user = User_Adapter::getInstance($session->get_usr_id(), appbox::get_instance());
$watermark = !$user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark)
{
if (basket_element_adapter::is_in_validation_session($record, $user))
{
$watermark = false;
}
elseif (basket_element_adapter::has_been_received($record, $user))
{
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
}
else
{
$collection = collection::get_from_base_id($record->get_base_id());
switch ($collection->get_pub_wm())
{
default:
case 'none':
$watermark = false;
break;
case 'stamp':
$stamp = true;
break;
case 'wm':
$watermark = false;
break;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
}
)
->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->error(function (\Exception $e)
{
if ($e instanceof Exception_Session_NotAuthenticated)
{
$code = 403;
$message = 'Forbidden';
}
elseif ($e instanceof Exception_NotAllowed)
{
$code = 403;
$message = 'Forbidden';
}
elseif ($e instanceof Exception_NotFound)
{
$code = 404;
$message = 'Not Found';
}
else
{
$code = 404;
$message = 'Not Found';
}
return new Response($message, $code);
});
return $app;
}
);

View File

@@ -1,80 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\Application;
return call_user_func(function()
{
$twig = new supertwig();
$app = new Application();
$app->mount('/records/edit', new Controller_Prod_Records_Edit());
$app->mount('/records/movecollection', new Controller_Prod_Records_MoveCollection());
$app->mount('/bridge/', new Controller_Prod_Records_Bridge());
$app->mount('/feeds', new Controller_Prod_Records_Feed());
$app->mount('/tooltip', new Controller_Prod_Records_Tooltip());
$app->error(function (\Exception $e, $code) use ($app, $twig)
{
if ($e instanceof Bridge_Exception)
{
$request = $app['request'];
$params = array(
'message' => $e->getMessage()
, 'file' => $e->getFile()
, 'line' => $e->getLine()
, 'r_method' => $request->getMethod()
, 'r_action' => $request->getRequestUri()
, 'r_parameters' => ($request->getMethod() == 'GET' ? array() : $request->request->all())
);
if ($e instanceof Bridge_Exception_ApiConnectorNotConfigured)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/notconfigured.twig', $params), 200);
}
elseif ($e instanceof Bridge_Exception_ApiConnectorNotConnected)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
}
elseif ($e instanceof Bridge_Exception_ApiConnectorAccessTokenFailed)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
}
elseif ($e instanceof Bridge_Exception_ApiDisabled)
{
$params = array_merge($params, array('api' => $e->get_api()));
return new response($twig->render('/prod/actions/Bridge/deactivated.twig', $params), 200);
}
return new response($twig->render('/prod/actions/Bridge/error.twig', $params), 200);
}
});
return $app;
});

View File

@@ -1,79 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Silex\Application;
return call_user_func(function()
{
$app = new Application();
if (!setup::is_installed())
{
return $app->redirect("/setup/")->send();
}
$app->get('/', function() use ($app)
{
$browser = Browser::getInstance();
if ($browser->isMobile())
return $app->redirect("/login/?redirect=/lightbox");
elseif ($browser->isNewGeneration())
return $app->redirect("/login/?redirect=/prod");
else
return $app->redirect("/login/?redirect=/client");
});
$app->get('robots.txt', function() use ($app)
{
require dirname(__FILE__) . "/../lib/bootstrap.php";
$appbox = appbox::get_instance();
$registry = $appbox->get_registry();
if ($registry->get('GV_allow_search_engine') === true)
{
$buffer = "User-Agent: *\n"
. "Allow: /\n";
}
else
{
$buffer = "User-Agent: *\n"
. "Disallow: /\n";
}
$response = new Response($buffer, 200, array('Content-Type: text/plain'));
$response->setCharset('UTF-8');
return $response;
});
$app->mount('/feeds/', new Controller_RSSFeeds());
/**
* Mount all aps
*/
return $app;
}
);

View File

@@ -1,83 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\Application;
return call_user_func(function()
{
$app = new Silex\Application();
$app['install'] = false;
$app['upgrade'] = false;
$app->before(function($a) use ($app)
{
if (setup::is_installed())
{
$appbox = appbox::get_instance();
if (!$appbox->need_major_upgrade())
throw new Exception_Setup_PhraseaAlreadyInstalled();
$app['upgrade'] = true;
}
else
{
$app['install'] = true;
}
return;
});
$app->get('/', function() use ($app)
{
if ($app['install'] === true)
return $app->redirect('/setup/installer/');
if ($app['upgrade'] === true)
return $app->redirect('/setup/upgrader/');
});
$app->mount('/installer/', new Controller_Setup_Installer());
$app->mount('/upgrader/', new Controller_Setup_Upgrader());
$app->mount('/test', new Controller_Utils_PathFileTest());
$app->mount('/connection_test', new Controller_Utils_ConnectionTest());
$app->error(function($e) use ($app)
{
if ($e instanceof Exception_Setup_PhraseaAlreadyInstalled)
return $app->redirect('/login');
return new Response(
sprintf(
'Error %s @%s:%s'
, $e->getFile()
, $e->getLine()
, $e->getMessage()
)
, 500
);
});
return $app;
});

View File

@@ -20,7 +20,7 @@ class module_admin
function getTree($position=false)
{
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$session = $appbox->get_session();
$usr_id = $session->get_usr_id();
@@ -76,7 +76,9 @@ class module_admin
, 'off_databoxes' => $off_databoxes
);
$twig = new supertwig();
$core = \bootstrap::getCore();
$twig = $core->getTwig();
return $twig->render('admin/tree.html.twig', $params);

View File

@@ -1,213 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_admin_route_users
{
protected $request;
/**
*
* @var array
*/
protected $results;
/**
*
* @var array
*/
protected $query_parms;
/**
*
* @var int
*/
protected $usr_id;
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
$this->request = $request;
return $this;
}
public function export(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$offset_start = (int) $request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
$this->query_parms = array(
'inactives' => $request->get('inactives')
, 'like_field' => $request->get('like_field')
, 'like_value' => $request->get('like_value')
, 'sbas_id' => $request->get('sbas_id')
, 'base_id' => $request->get('base_id')
, 'srt' => $request->get("srt", User_Query::SORT_CREATIONDATE)
, 'ord' => $request->get("ord", User_Query::ORD_DESC)
, 'offset_start' => 0
);
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$query = new User_Query($appbox);
if (is_array($this->query_parms['base_id']))
$query->on_base_ids($this->query_parms['base_id']);
elseif (is_array($this->query_parms['sbas_id']))
$query->on_sbas_ids($this->query_parms['sbas_id']);
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"])
->like($this->query_parms['like_field'], $this->query_parms['like_value'])
->get_inactives($this->query_parms['inactives'])
->include_templates(false)
->on_bases_where_i_am($user->ACL(), array('canadmin'))
->execute();
return $this->results->get_results();
}
public function search(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$offset_start = (int) $request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
$results_quantity = (int) $request->get('per_page');
$results_quantity = ($results_quantity < 10 || $results_quantity > 50) ? 20 : $results_quantity;
$this->query_parms = array(
'inactives' => $request->get('inactives')
, 'like_field' => $request->get('like_field')
, 'like_value' => $request->get('like_value')
, 'sbas_id' => $request->get('sbas_id')
, 'base_id' => $request->get('base_id')
, 'srt' => $request->get("srt", User_Query::SORT_CREATIONDATE)
, 'ord' => $request->get("ord", User_Query::ORD_DESC)
, 'per_page' => $results_quantity
, 'offset_start' => $offset_start
);
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$query = new User_Query($appbox);
if (is_array($this->query_parms['base_id']))
$query->on_base_ids($this->query_parms['base_id']);
elseif (is_array($this->query_parms['sbas_id']))
$query->on_sbas_ids($this->query_parms['sbas_id']);
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"])
->like($this->query_parms['like_field'], $this->query_parms['like_value'])
->get_inactives($this->query_parms['inactives'])
->include_templates(true)
->on_bases_where_i_am($user->ACL(), array('canadmin'))
->limit($offset_start, $results_quantity)
->execute();
try
{
$invite_id = User_Adapter::get_usr_id_from_login('invite');
$invite = User_Adapter::getInstance($invite_id, $appbox);
}
catch (Exception $e)
{
$invite = User_Adapter::create($appbox, 'invite', 'invite', '', false);
}
try
{
$autoregister_id = User_Adapter::get_usr_id_from_login('autoregister');
$autoregister = User_Adapter::getInstance($autoregister_id, $appbox);
}
catch (Exception $e)
{
$autoregister = User_Adapter::create($appbox, 'autoregister', 'autoregister', '', false);
}
foreach ($this->query_parms as $k => $v)
{
if (is_null($v))
$this->query_parms[$k] = false;
}
$query = new User_Query($appbox);
$templates = $query
->only_templates(true)
->execute()->get_results();
return array(
'users' => $this->results,
'parm' => $this->query_parms,
'invite_user' => $invite,
'autoregister_user' => $autoregister,
'templates' => $templates
);
}
public function create_newuser()
{
$email = $this->request->get('value');
if(!mail::validateEmail($email))
{
throw new Exception_InvalidArgument(_('Invalid mail address'));
}
$appbox = appbox::get_instance();
$conn = $appbox->get_connection();
$sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = count($row);
if (!is_array($row) || $count == 0)
{
$created_user = User_Adapter::create($appbox, $email, random::generatePassword(16), $email, false, false);
$this->usr_id = $created_user->get_id();
}
else
{
$this->usr_id = $row['usr_id'];
$created_user = User_Adapter::getInstance($this->usr_id, $appbox);
}
return $created_user;
}
public function create_template()
{
$name = $this->request->get('value');
if(trim($name) === '')
{
throw new Exception_InvalidArgument(_('Invalid template name'));
}
$appbox = appbox::get_instance();
$user = User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$created_user = User_Adapter::create($appbox, $name, random::generatePassword(16), null, false, false);
$created_user->set_template($user);
$this->usr_id = $user->get_id();
return $created_user;
}
}

View File

@@ -1,679 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_admin_route_users_edit
{
protected $request;
/**
*
* @var array
*/
protected $users = array();
/**
*
* @var array
*/
protected $users_datas;
/**
*
* @var int
*/
protected $base_id;
/**
*
* @param Symfony\Component\HttpFoundation\Request $request
* @return module_admin_route_users_edit
*/
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
$this->users = explode(';', $request->get('users'));
$this->request = $request;
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$users = array();
foreach ($this->users as $usr_id)
{
$usr_id = (int) $usr_id;
if ($usr_id > 0)
$users[$usr_id] = $usr_id;
}
$this->users = $users;
return $this;
}
public function delete_users()
{
$appbox = appbox::get_instance();
foreach ($this->users as $usr_id)
{
$user = User_Adapter::getInstance($usr_id, $appbox);
$this->delete_user($user);
}
return $this;
}
protected function delete_user(User_Adapter $user)
{
$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')));
$user->ACL()->revoke_access_from_bases($list);
if ($user->ACL()->is_phantom())
$user->delete();
return $this;
}
public function get_users_rights()
{
$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')));
$sql = "SELECT
b.sbas_id,
b.base_id,
sum(actif) as actif,
sum(canputinalbum) as canputinalbum,
sum(candwnldpreview) as candwnldpreview,
sum(candwnldhd) as candwnldhd,
sum(cancmd) as cancmd,
sum(nowatermark) as nowatermark,
sum(canaddrecord) as canaddrecord,
sum(canmodifrecord) as canmodifrecord,
sum(chgstatus) as chgstatus,
sum(candeleterecord) as candeleterecord,
sum(imgtools) as imgtools,
sum(canadmin) as canadmin,
sum(canreport) as canreport,
sum(canpush) as canpush,
sum(manage) as manage,
sum(modify_struct) as modify_struct,
sum(sbu.bas_modif_th) as bas_modif_th,
sum(sbu.bas_manage) as bas_manage,
sum(sbu.bas_modify_struct) as bas_modify_struct,
sum(sbu.bas_chupub) as bas_chupub,
sum(time_limited) as time_limited,
DATE_FORMAT(limited_from,'%Y%m%d') as limited_from,
DATE_FORMAT(limited_to,'%Y%m%d') as limited_to,
sum(restrict_dwnld) as restrict_dwnld,
sum(remain_dwnld) as remain_dwnld,
sum(month_dwnld_max) as month_dwnld_max,
mask_xor as maskxordec,
bin(mask_xor) as maskxorbin,
mask_and as maskanddec,
bin(mask_and) as maskandbin
FROM (usr u, bas b, sbas s)
LEFT JOIN (basusr bu)
ON (bu.base_id = b.base_id AND u.usr_id = bu.usr_id)
LEFT join sbasusr sbu
ON (sbu.sbas_id = b.sbas_id AND u.usr_id = sbu.usr_id)
WHERE ( (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . " )
AND b.sbas_id = s.sbas_id
AND (b.base_id = '" . implode("' OR b.base_id = '", $list) . "'))
GROUP BY b.base_id
ORDER BY s.ord, s.sbas_id, b.ord, b.base_id ";
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = 'SELECT base_id, sum(1) as access FROM basusr
WHERE (usr_id = ' . implode(' OR usr_id = ', $this->users) . ')
AND (base_id = ' . implode(' OR base_id = ', $list) . ')
GROUP BY base_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$access = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$base_ids = array();
foreach ($access as $acc)
{
$base_ids[$acc['base_id']] = $acc;
}
unset($access);
foreach ($rs as $k => $row)
{
$rs[$k]['access'] = array_key_exists($row['base_id'], $base_ids) ? $base_ids[$row['base_id']]['access'] : '0';
foreach ($row as $dk => $data)
{
if (is_null($data))
$rs[$k][$dk] = '0';
}
}
$query = new User_Query($appbox);
$templates = $query
->only_templates(true)
->execute()->get_results();
$this->users_datas = $rs;
$out = array(
'datas' => $this->users_datas,
'users' => $this->users,
'users_serial' => implode(';', $this->users),
'base_id' => $this->base_id,
'main_user' => null,
'templates'=>$templates
);
if (count($this->users) == 1)
{
$usr_id = array_pop($this->users);
$out['main_user'] = User_Adapter::getInstance($usr_id, $appbox);
}
return $out;
}
public function get_quotas()
{
$this->base_id = (int) $this->request->get('base_id');
// $this->base_id = (int) $parm['base_id'];
$sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
WHERE u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . "
AND bu.base_id = :base_id";
$conn = connection::getPDOConnection();
$stmt = $conn->prepare($sql);
$stmt->execute(array(':base_id' => $this->base_id));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->users_datas = $rs;
return array(
'datas' => $this->users_datas,
'users' => $this->users,
'users_serial' => implode(';', $this->users),
'base_id' => $this->base_id
);
}
public function get_masks()
{
$this->base_id = (int) $this->request->get('base_id');
$sql = "SELECT BIN(mask_and) AS mask_and, BIN(mask_xor) AS mask_xor
FROM basusr
WHERE usr_id IN (" . implode(',', $this->users) . ")
AND base_id = :base_id";
$conn = connection::getPDOConnection();
$stmt = $conn->prepare($sql);
$stmt->execute(array(':base_id' => $this->base_id));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$msk_and = null;
$msk_xor = null;
$tbits_and = array();
$tbits_xor = array();
$nrows = 0;
for ($bit = 0; $bit < 64; $bit++)
$tbits_and[$bit] = $tbits_xor[$bit] = array("nset" => 0);
foreach ($rs as $row)
{
$sta_xor = strrev($row["mask_xor"]);
for ($bit = 0; $bit < strlen($sta_xor); $bit++)
$tbits_xor[$bit]["nset"] += substr($sta_xor, $bit, 1) != "0" ? 1 : 0;
$sta_and = strrev($row["mask_and"]);
for ($bit = 0; $bit < strlen($sta_and); $bit++)
$tbits_and[$bit]["nset"] += substr($sta_and, $bit, 1) != "0" ? 1 : 0;
$nrows++;
}
$tbits_left = array();
$tbits_right = array();
$sbas_id = phrasea::sbasFromBas($this->base_id);
$databox = databox::get_instance($sbas_id);
$status = $databox->get_statusbits();
foreach ($status as $bit => $datas)
{
$tbits_left[$bit]["nset"] = 0;
$tbits_left[$bit]["name"] = $datas["labeloff"];
$tbits_left[$bit]["icon"] = $datas["img_off"];
$tbits_right[$bit]["nset"] = 0;
$tbits_right[$bit]["name"] = $datas["labelon"];
$tbits_right[$bit]["icon"] = $datas["img_on"];
}
$vand_and = $vand_or = $vxor_and = $vxor_or = "0000";
for ($bit = 4; $bit < 64; $bit++)
{
if (($tbits_and[$bit]["nset"] != 0 && $tbits_and[$bit]["nset"] != $nrows) || ($tbits_xor[$bit]["nset"] != 0 && $tbits_xor[$bit]["nset"] != $nrows))
{
if (isset($tbits_left[$bit]) && isset($tbits_right[$bit]))
{
$tbits_left[$bit]["nset"] = 2;
$tbits_right[$bit]["nset"] = 2;
}
$vand_and = "1" . $vand_and;
$vand_or = "0" . $vand_or;
$vxor_and = "1" . $vxor_and;
$vxor_or = "0" . $vxor_or;
}
else
{
if (isset($tbits_left[$bit]) && isset($tbits_right[$bit]))
{
$tbits_left[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == 0) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
$tbits_right[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == $nrows) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
}
$vand_and = ($tbits_and[$bit]["nset"] == 0 ? "0" : "1") . $vand_and;
$vand_or = ($tbits_and[$bit]["nset"] == $nrows ? "1" : "0") . $vand_or;
$vxor_and = ($tbits_xor[$bit]["nset"] == 0 ? "0" : "1") . $vxor_and;
$vxor_or = ($tbits_xor[$bit]["nset"] == $nrows ? "1" : "0") . $vxor_or;
}
}
$this->users_datas = array(
'tbits_left' => $tbits_left,
'tbits_right' => $tbits_right,
'vand_and' => $vand_and,
'vand_or' => $vand_or,
'vxor_and' => $vxor_and,
'vxor_or' => $vxor_or
);
return array(
'datas' => $this->users_datas,
'users' => $this->users,
'users_serial' => implode(';', $this->users),
'base_id' => $this->base_id
);
}
public function get_time()
{
$this->base_id = (int) $this->request->get('base_id');
$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)
WHERE u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . "
AND bu.base_id = :base_id";
$conn = connection::getPDOConnection();
$stmt = $conn->prepare($sql);
$stmt->execute(array(':base_id' => $this->base_id));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$time_limited = -1;
$limited_from = $limited_to = false;
foreach ($rs as $row)
{
if ($time_limited < 0)
$time_limited = $row['time_limited'];
if ($time_limited < 2 && $row['time_limited'] != $row['time_limited'])
$time_limited = 2;
if ($limited_from !== '' && trim($row['limited_from']) != '0000-00-00 00:00:00')
{
$limited_from = $limited_from === false ? $row['limited_from'] : (($limited_from == $row['limited_from']) ? $limited_from : '');
}
if ($limited_to !== '' && trim($row['limited_to']) != '0000-00-00 00:00:00')
{
$limited_to = $limited_to === false ? $row['limited_to'] : (($limited_to == $row['limited_to']) ? $limited_to : '');
}
}
if ($limited_from)
{
$date_obj_from = new DateTime($limited_from);
$limited_from = $date_obj_from->format('Y-m-d');
}
if ($limited_to)
{
$date_obj_to = new DateTime($limited_to);
$limited_to = $date_obj_to->format('Y-m-d');
}
$datas = array('time_limited' => $time_limited, 'limited_from' => $limited_from, 'limited_to' => $limited_to);
$this->users_datas = $datas;
return array(
'datas' => $this->users_datas,
'users' => $this->users,
'users_serial' => implode(';', $this->users),
'base_id' => $this->base_id
);
}
public function apply_rights()
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$request = http_request::getInstance();
$ACL = User_Adapter::getInstance($session->get_usr_id(), $appbox)->ACL();
$base_ids = array_keys($ACL->get_granted_base(array('canadmin')));
$update = $create = $delete = $create_sbas = $update_sbas = array();
foreach ($base_ids as $base_id)
{
$rights = array(
'access',
'actif',
'canputinalbum',
'nowatermark',
'candwnldpreview',
'candwnldhd',
'cancmd',
'canaddrecord',
'canmodifrecord',
'chgstatus',
'candeleterecord',
'imgtools',
'canadmin',
'canreport',
'canpush',
'manage',
'modify_struct'
);
foreach ($rights as $k => $right)
{
if (($right == 'access' && !$ACL->has_access_to_base($base_id))
|| ($right != 'access' && !$ACL->has_right_on_base($base_id, $right)))
{
unset($rights[$k]);
continue;
}
$rights[$k] = $right . '_' . $base_id;
}
$parm = $request->get_parms_from_serialized_datas($rights, 'values');
foreach ($parm as $p => $v)
{
if (trim($v) == '')
continue;
$serial = explode('_', $p);
$base_id = array_pop($serial);
$p = implode('_', $serial);
if ($p == 'access')
{
if ($v === '1')
{
$create_sbas[phrasea::sbasFromBas($base_id)] = phrasea::sbasFromBas($base_id);
$create[] = $base_id;
}
else
$delete[] = $base_id;
}
else
{
$create_sbas[phrasea::sbasFromBas($base_id)] = phrasea::sbasFromBas($base_id);
$update[$base_id][$p] = $v;
}
}
}
$sbas_ids = $ACL->get_granted_sbas();
foreach ($sbas_ids as $databox)
{
$rights = array(
'bas_modif_th',
'bas_manage',
'bas_modify_struct',
'bas_chupub'
);
foreach ($rights as $k => $right)
{
if (!$ACL->has_right_on_sbas($databox->get_sbas_id(), $right))
{
unset($rights[$k]);
continue;
}
$rights[$k] = $right . '_' . $databox->get_sbas_id();
}
$parm = $request->get_parms_from_serialized_datas($rights, 'values');
foreach ($parm as $p => $v)
{
if (trim($v) == '')
continue;
$serial = explode('_', $p);
$sbas_id = array_pop($serial);
$p = implode('_', $serial);
$update_sbas[$sbas_id][$p] = $v;
}
}
foreach ($this->users as $usr_id)
{
try
{
$appbox->get_connection()->beginTransaction();
$user = User_Adapter::getInstance($usr_id, $appbox);
$user->ACL()->revoke_access_from_bases($delete)
->give_access_to_base($create)
->give_access_to_sbas($create_sbas);
foreach ($update as $base_id => $rights)
{
$user->ACL()->update_rights_to_base($base_id, $rights);
}
foreach ($update_sbas as $sbas_id => $rights)
{
$user->ACL()->update_rights_to_sbas($sbas_id, $rights);
}
$appbox->get_connection()->commit();
$user->ACL()->revoke_unused_sbas_rights();
unset($user);
}
catch (Exception $e)
{
$appbox->get_connection()->rollBack();
}
}
return $this;
}
public function apply_infos()
{
if (count($this->users) != 1)
{
return $this;
}
$users = $this->users;
$user = User_adapter::getInstance(array_pop($users), appbox::get_instance());
if ($user->is_template() || $user->is_special())
{
return $this;
}
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$request = http_request::getInstance();
$infos = array(
'gender'
, 'first_name'
, 'last_name'
, 'email'
, 'address'
, 'zip'
, 'geonameid'
, 'function'
, 'company'
, 'activite'
, 'telephone'
, 'fax'
);
$parm = $request->get_parms_from_serialized_datas($infos, 'user_infos');
if ($parm['email'] && !mail::validateEmail($parm['email']))
throw new Exception_InvalidArgument(_('Email addess is not valid'));
$user->set_firstname($parm['first_name'])
->set_lastname($parm['last_name'])
->set_email($parm['email'])
->set_address($parm['address'])
->set_zip($parm['zip'])
->set_geonameid($parm['geonameid'])
->set_position($parm['function'])
->set_job($parm['activite'])
->set_company($parm['company'])
->set_tel($parm['telephone'])
->set_fax($parm['fax']);
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()
{
$this->base_id = (int) $this->request->get('base_id');
foreach ($this->users as $usr_id)
{
$user = User_Adapter::getInstance($usr_id, appbox::get_instance());
if ($this->request->get('quota'))
$user->ACL()->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes'));
else
$user->ACL()->remove_quotas_on_base($this->base_id);
}
return $this;
}
public function apply_masks()
{
$this->base_id = (int) $this->request->get('base_id');
$vand_and = $this->request->get('vand_and');
$vand_or = $this->request->get('vand_or');
$vxor_and = $this->request->get('vxor_and');
$vxor_or = $this->request->get('vxor_or');
if ($vand_and && $vand_or && $vxor_and && $vxor_or)
{
foreach ($this->users as $usr_id)
{
$user = User_Adapter::getInstance($usr_id, appbox::get_instance());
$user->ACL()->set_masks_on_base($this->base_id, $vand_and, $vand_or, $vxor_and, $vxor_or);
}
}
return $this;
}
public function apply_time()
{
$this->base_id = (int) $this->request->get('base_id');
$dmin = $this->request->get('dmin') ? new DateTime($this->request->get('dmin')) : null;
$dmax = $this->request->get('dmax') ? new DateTime($this->request->get('dmax')) : null;
$activate = $this->request->get('limit');
foreach ($this->users as $usr_id)
{
$user = User_Adapter::getInstance($usr_id, appbox::get_instance());
$user->ACL()->set_limits($this->base_id, $activate, $dmin, $dmax);
}
}
}

View File

@@ -1,433 +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 OAuth2 Connector
*
* @see http://oauth.net/2/
* @uses http://code.google.com/p/oauth2-php/
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
require_once dirname(__FILE__) . "/../../../../lib/bootstrap.php";
require_once dirname(__FILE__) . "/../../../../lib/classes/API/OAuth2/Autoloader.class.php";
bootstrap::register_autoloads();
API_OAuth2_Autoloader::register();
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return call_user_func(function()
{
$app = new Silex\Application();
$app->register(new Silex\Provider\ValidatorServiceProvider(), array(
'validator.class_path' => __DIR__ . '/../../../../lib/vendor/symfony/src',
));
$app['appbox'] = function()
{
return appbox::get_instance();
};
$app['supertwig'] = $app->share(function()
{
$twig = new supertwig();
$twig->addFilter(array('prettyDate' => 'phraseadate::getPrettyString'));
return $twig;
});
$app['oauth'] = function($app)
{
return new API_OAuth2_Adapter($app['appbox']);
};
$app['user'] = function($app)
{
if ($app['appbox']->get_session()->is_authenticated())
{
$user = user_adapter::getInstance(
$app['appbox']->get_session()->get_usr_id()
, $app['appbox']
);
return $user;
}
else
{
return null;
}
};
/**
* Protected Closure
* @var Closure
* @return Symfony\Component\HttpFoundation\Response
*/
$app['response'] = $app->protect(function ($template, $variable) use ($app)
{
$response = new Response(
$app['supertwig']->render($template, $variable)
, 200
, array('Content-Type' => 'text/html')
);
$response->setCharset('UTF-8');
return $response;
});
/* * *******************************************************************
* AUTHENTIFICATION API
*/
/**
* AUTHORIZE ENDPOINT
*
* Authorization endpoint - used to obtain authorization from the
* resource owner via user-agent redirection.
*/
$authorize_func = function() use ($app)
{
$request = $app['request'];
$oauth2_adapter = $app['oauth'];
$twig = $app['supertwig'];
$session = $app['appbox']->get_session();
//Check for auth params, send error or redirect if not valid
$params = $oauth2_adapter->getAuthorizationRequestParameters($request);
$authenticated = $session->is_authenticated();
$app_authorized = false;
$errorMessage = false;
$client = API_OAuth2_Application::load_from_client_id($app['appbox'], $params['client_id']);
$oauth2_adapter->setClient($client);
$action_accept = $request->get("action_accept", null);
$action_login = $request->get("action_login", null);
$template = "api/auth/end_user_authorization.twig";
$custom_template = $app['appbox']->get_registry()->get('GV_RootPath') . 'config/templates/web/api/auth/end_user_authorization/' . $client->get_id() . '.twig';
if (file_exists($custom_template))
{
$template = 'api/auth/end_user_authorization/' . $client->get_id() . '.twig';
}
if (!$authenticated)
{
if ($action_login !== null)
{
try
{
$login = $request->get("login");
$password = $request->get("password");
$auth = new Session_Authentication_Native($app['appbox'], $login, $password);
$session->authenticate($auth);
}
catch (Exception $e)
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => true
, "user" => $app['user']
);
$html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
}
else
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['user']
);
$html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
}
//check if current client is alreadu authorized by current user
$user_auth_clients = API_OAuth2_Application::load_authorized_app_by_user($app['appbox'], $app['user']);
foreach ($user_auth_clients as $auth_client)
{
if ($client->get_client_id() == $auth_client->get_client_id())
$app_authorized = true;
}
$account = $oauth2_adapter->updateAccount($session->get_usr_id());
$params['account_id'] = $account->get_id();
if (!$app_authorized && $action_accept === null)
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['user']
);
$html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
elseif (!$app_authorized && $action_accept !== null)
{
$app_authorized = !!$action_accept;
$account->set_revoked(!$app_authorized);
}
//if native app show template
if ($oauth2_adapter->isNativeApp($params['redirect_uri']))
{
$params = $oauth2_adapter->finishNativeClientAuthorization($app_authorized, $params);
$html = $twig->render("api/auth/native_app_access_token.twig", $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
else
{
$oauth2_adapter->finishClientAuthorization($app_authorized, $params);
}
};
$route = '/authorize';
$app->get($route, $authorize_func);
$app->post($route, $authorize_func);
/**
* TOKEN ENDPOINT
* Token endpoint - used to exchange an authorization grant for an access token.
*/
$route = '/token';
$app->post($route, function() use ($app)
{
$app['oauth']->grantAccessToken();
ob_flush();
flush();
return;
});
/**
* MANAGEMENT APPS
*
*
*/
/**
* list of all authorized apps by logged user
*/
$route = '/applications';
$app->get($route, function() use ($app)
{
$apps = API_OAuth2_Application::load_app_by_user($app['appbox'], $app['user']);
return $app['response']('api/auth/applications.twig', array("apps" => $apps, 'user' => $app['user']));
});
/**
* list of apps created by user
*/
$route = "/applications/dev";
$app->get($route, function() use ($app)
{
$rs = API_OAuth2_Application::load_dev_app_by_user($app['appbox'], $app['user']);
return $app['response']('api/auth/application_dev.twig', array("apps" => $rs));
});
/**
* display a new app form
*/
$route = "/applications/dev/new";
$app->get($route, function() use ($app)
{
$var = array("violations" => null);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
$route = "/applications/dev/create";
$app->post($route, function() use ($app)
{
$submit = false;
$post = new API_OAuth2_Form_DevApp($app['request']);
$violations = $app['validator']->validate($post);
if ($violations->count() == 0)
$submit = true;
$request = $app['request'];
if ($submit)
{
$application = API_OAuth2_Application::create($app['appbox'], $app['user'], $request->get('name'));
$application->set_description($request->get('description'))
->set_redirect_uri($request->get('callback'))
->set_type($request->get('type'))
->set_website($request->get('website'));
return $app->redirect("/api/oauthv2/applications/dev/" . $application->get_id() . "/show");
}
$var = array(
"violations" => $violations,
"form" => $post
);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
/**
* show details of app identified by its id
*/
$route = "/applications/dev/{id}/show";
$app->get($route, function($id) use ($app)
{
$client = new API_OAuth2_Application($app['appbox'], $id);
$token = $client->get_user_account($app['user'])->get_token()->get_value();
$var = array("app" => $client, "user" => $app['user'], "token" => $token);
return $app['response']('api/auth/application_dev_show.twig', $var);
});
/**
* revoke access from a user to the app
* identified by account id
*/
$route = "/applications/revoke_access/";
$app->post($route, function() use ($app)
{
$result = array("ok" => false);
try
{
$account = new API_OAuth2_Account($app['appbox'], $app['request']->get('account_id'));
$account->set_revoked((bool) $app['request']->get('revoke'));
$result['ok'] = true;
}
catch (Exception $e)
{
}
return new Response(json_encode($result), 200, array("content-type" => "application/json"));
});
$route = "/applications/{id}/generate_access_token/";
$app->post($route, function($id) use ($app)
{
$result = array("ok" => false);
try
{
$client = new API_OAuth2_Application($app['appbox'], $id);
$account = $client->get_user_account($app['user']);
$token = $account->get_token();
if ($token instanceof API_OAuth2_Token)
$token->renew();
else
$token = API_OAuth2_Token::create($app['appbox'], $account);
$result = array(
"ok" => true
, 'token' => $token->get_value()
);
}
catch (Exception $e)
{
}
return new response(json_encode($result), 200, array("content-type" => "application/json"));
});
$route = "/applications/oauth_callback";
$app->post($route, function() use ($app)
{
$app_id = $app['request']->request->get("app_id");
$app_callback = $app["request"]->request->get("callback");
$result = array("success" => false);
try
{
$client = new API_OAuth2_Application($app['appbox'], $app_id);
$client->set_redirect_uri($app_callback);
$result['success'] = true;
}
catch (Exception $e)
{
}
return new Response(json_encode($result), 200, array("content-type" => "application/json"));
});
$route = "/applications/{id}";
$app->delete($route, function($id) use ($app)
{
$result = array("success" => false);
try
{
$client = new API_OAuth2_Application($app['appbox'], $id);
$client->delete();
$result['success'] = true;
}
catch (Exception $e)
{
}
return new Response(json_encode($result), 200, array("content-type" => "application/json"));
});
/**
* *******************************************************************
*
* Route Errors
*
*/
$app->error(function (Exception $e) use ($app)
{
if ($e instanceof NotFoundHttpException || $e instanceof Exception_NotFound)
{
return new Response('The requested page could not be found.', 404);
}
$code = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
return new Response('We are sorry, but something went terribly wrong.<br />' . $e->getMessage(), $code);
});
return $app;
});

View File

@@ -1,750 +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 APIv1
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
/**
* Application Routage for API v1
*/
require_once dirname(__FILE__) . "/../../../../lib/classes/API/OAuth2/Autoloader.class.php";
require_once dirname(__FILE__) . "/../../../../lib/bootstrap.php";
bootstrap::register_autoloads();
API_OAuth2_Autoloader::register();
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception;
return call_user_func(function(){
$app = new Silex\Application();
$app["appbox"] = appbox::get_instance();
/**
* Associated user to related token
* @var User_Adapter
*/
$app['p4user'] = null;
/**
* @var API_OAuth2_Token
*/
$app['token'] = null;
/**
* Protected Closure
* @var Closure
* @return Symfony\Component\HttpFoundation\Response
*/
$app['response'] = $app->protect(function ($result)
{
$response = new Response(
$result->format()
, $result->get_http_code()
, array('Content-Type' => $result->get_content_type())
);
$response->setCharset('UTF-8');
return $response;
});
/**
* Api Service
* @var Closure
*/
$app['api'] = function () use ($app)
{
return new API_V1_adapter(false, $app["appbox"]);
};
$parseRoute = function ($route, Response $response)
{
$ressource = $general = $aspect = $action = null;
$exploded_route = explode('/', p4string::delFirstSlash((p4string::delEndSlash($route))));
if (sizeof($exploded_route) > 0 && $response->isOk())
{
$ressource = $exploded_route[0];
if (sizeof($exploded_route) == 2 && (int) $exploded_route[1] == 0)
{
$general = $exploded_route[1];
}
else
{
switch ($ressource)
{
case API_V1_Log::DATABOXES_RESSOURCE :
if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
$aspect = $exploded_route[2];
break;
case API_V1_Log::RECORDS_RESSOURCE :
if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 4)
{
if (!isset($exploded_route[3]))
$aspect = "record";
elseif (preg_match("/^set/", $exploded_route[3]))
$action = $exploded_route[3];
else
$aspect = $exploded_route[3];
}
break;
case API_V1_Log::BASKETS_RESSOURCE :
if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
{
if (preg_match("/^set/", $exploded_route[2]) || preg_match("/^delete/", $exploded_route[2]))
$action = $exploded_route[2];
else
$aspect = $exploded_route[2];
}
break;
case API_V1_Log::FEEDS_RESSOURCE :
if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
$aspect = $exploded_route[2];
break;
}
}
}
return array('ressource' => $ressource, 'general' => $general, 'aspect' => $aspect, 'action' => $action);
};
/**
* oAuth verification process
*/
$app->before(function($request) use ($app)
{
$session = $app["appbox"]->get_session();
$oauth2_adapter = new API_OAuth2_Adapter($app["appbox"]);
$oauth2_adapter->verifyAccessToken();
$app['p4user'] = User_Adapter::getInstance($oauth2_adapter->get_usr_id(), $app["appbox"]);
$app['token'] = API_OAuth2_Token::load_by_oauth_token($app["appbox"], $oauth2_adapter->getToken());
if ($session->is_authenticated())
return;
if ($oauth2_adapter->has_ses_id())
{
try
{
$session->restore($app['p4user'], $oauth2_adapter->get_ses_id());
return;
}
catch (\Exception $e)
{
}
}
$auth = new Session_Authentication_None($app['p4user']);
$session->authenticate($auth);
$oauth2_adapter->remember_this_ses_id($session->get_ses_id());
return;
});
/**
* oAUth log process
*/
$app->after(function (Request $request, Response $response) use ($app, $parseRoute)
{
$account = $app['token']->get_account();
$pathInfo = $request->getPathInfo();
$route = $parseRoute($pathInfo, $response);
$log = API_V1_Log::create(
$app["appbox"],
$account,
$request->getMethod() . " " . $pathInfo,
$response->getStatusCode(),
$response->headers->get('content-type'),
$route['ressource'],
$route['general'],
$route['aspect'],
$route['action']);
});
/**
* Method Not Allowed Closure
*/
$bad_request_exception = function()
{
throw new API_V1_exception_badrequest();
};
/**
* *******************************************************************
* Route : /databoxes/list/FORMAT/
*
* Method : GET
*
* Parameters :
*
*/
$route = '/databoxes/list/';
$app->get(
$route, function() use ($app)
{
return $app['response']($app['api']->get_databoxes($app['request']));
}
);
/**
* *******************************************************************
*
* Route /databoxes/DATABOX_ID/collections/FORMAT/
*
* Method : GET
*
* Parameters ;
* DATABOX_ID : required INT
*/
$route = '/databoxes/{databox_id}/collections/';
$app->get(
$route, function($databox_id) use ($app)
{
$result = $app['api']->get_databox_collections($app['request'], $databox_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+');
$app->get('/databoxes/{any_id}/collections/', $bad_request_exception);
/**
* *******************************************************************
* Route /databoxes/DATABOX_ID/status/FORMAT/
*
* Method : GET
*
* Parameters ;
* DATABOX_ID : required INT
*
*/
$route = '/databoxes/{databox_id}/status/';
$app->get(
$route, function($databox_id) use ($app)
{
$result = $app['api']->get_databox_status($app['request'], $databox_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+');
$app->get('/databoxes/{any_id}/status/', $bad_request_exception);
/**
* Route /databoxes/DATABOX_ID/metadatas/FORMAT/
*
* Method : GET
*
* Parameters ;
* DATABOX_ID : required INT
*/
$route = '/databoxes/{databox_id}/metadatas/';
$app->get(
$route, function($databox_id) use ($app)
{
$result = $app['api']->get_databox_metadatas($app['request'], $databox_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+');
$app->get('/databoxes/{any_id}/metadatas/', $bad_request_exception);
/**
* Route /databoxes/DATABOX_ID/termsOfUse/FORMAT/
*
* Method : GET
*
* Parameters ;
* DATABOX_ID : required INT
*/
$route = '/databoxes/{databox_id}/termsOfUse/';
$app->get(
$route, function($databox_id) use ($app)
{
$result = $app['api']->get_databox_terms($app['request'], $databox_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+');
$app->get('/databoxes/{any_id}/termsOfUse/', $bad_request_exception);
/**
* Route : /records/search/FORMAT/
*
* Method : GET or POST
*
* Parameters :
* bases[] : array
* status[] : array
* fields[] : array
* record_type : boolean
* media_type : string
*
* Response :
* Array of record objects
*
*/
$route = '/records/search/';
$app->post(
$route, function() use ($app)
{
$result = $app['api']->search_records($app['request']);
return $app['response']($result);
}
);
/**
* Route : /records/DATABOX_ID/RECORD_ID/metadatas/FORMAT/
*
* Method : GET
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/metadatas/';
$app->get(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->get_record_metadatas($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->get('/records/{any_id}/{anyother_id}/metadatas/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/status/FORMAT/
*
* Method : GET
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/status/';
$app->get(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->get_record_status($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->get('/records/{any_id}/{anyother_id}/status/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/related/FORMAT/
*
* Method : GET
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/related/';
$app->get(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->get_record_related($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->get('/records/{any_id}/{anyother_id}/related/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/embed/FORMAT/
*
* Method : GET
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/embed/';
$app->get(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->get_record_embed($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->get('/records/{any_id}/{anyother_id}/embed/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/FORMAT/
*
* Method : POST
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/setmetadatas/';
$app->post(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->set_record_metadatas($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->post('/records/{any_id}/{anyother_id}/setmetadatas/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/setstatus/FORMAT/
*
* Method : POST
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/setstatus/';
$app->post(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->set_record_status($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->post('/records/{any_id}/{anyother_id}/setstatus/', $bad_request_exception);
/**
* Route : /records/DATABOX_ID/RECORD_ID/setcollection/FORMAT/
*
* Method : POST
*
* Parameters :
* DATABOX_ID : required INT
* RECORD_ID : required INT
*
*/
$route = '/records/{databox_id}/{record_id}/setcollection/';
$app->post(
$route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->set_record_collection($app['request'], $databox_id, $record_id);
return $app['response']($result);
}
)->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->post('/records/{wrong_databox_id}/{wrong_record_id}/setcollection/', $bad_request_exception);
$route = '/records/{databox_id}/{record_id}/';
$app->get($route, function($databox_id, $record_id) use ($app)
{
$result = $app['api']->get_record($app['request'], $databox_id, $record_id);
return $app['response']($result);
})->assert('databox_id', '\d+')->assert('record_id', '\d+');
$app->get('/records/{any_id}/{anyother_id}/', $bad_request_exception);
/**
* Route : /baskets/list/FORMAT/
*
* Method : POST
*
* Parameters :
*
*/
$route = '/baskets/list/';
$app->get(
$route, function() use ($app)
{
$result = $app['api']->search_baskets($app['request']);
return $app['response']($result);
}
);
/**
* Route : /baskets/add/FORMAT/
*
* Method : POST
*
* Parameters :
*
*/
$route = '/baskets/add/';
$app->post(
$route, function() use ($app)
{
$result = $app['api']->create_basket($app['request']);
return $app['response']($result);
}
);
/**
* Route : /baskets/BASKET_ID/content/FORMAT/
*
* Method : GET
*
* Parameters :
* BASKET_ID : required INT
*
*/
$route = '/baskets/{basket_id}/content/';
$app->get(
$route, function($basket_id) use ($app)
{
$result = $app['api']->get_basket($app['request'], $basket_id);
return $app['response']($result);
}
)->assert('basket_id', '\d+');
$app->get('/baskets/{wrong_basket_id}/content/', $bad_request_exception);
/**
* Route : /baskets/BASKET_ID/settitle/FORMAT/
*
* Method : GET
*
* Parameters :
* BASKET_ID : required INT
*
*/
$route = '/baskets/{basket_id}/setname/';
$app->post(
$route, function($basket_id) use ($app)
{
$result = $app['api']->set_basket_title($app['request'], $basket_id);
return $app['response']($result);
}
)->assert('basket_id', '\d+');
$app->post('/baskets/{wrong_basket_id}/setname/', $bad_request_exception);
/**
* Route : /baskets/BASKET_ID/setdescription/FORMAT/
*
* Method : POST
*
* Parameters :
* BASKET_ID : required INT
*
*/
$route = '/baskets/{basket_id}/setdescription/';
$app->post(
$route, function($basket_id) use ($app)
{
$result = $app['api']->set_basket_description($app['request'], $basket_id);
return $app['response']($result);
}
)->assert('basket_id', '\d+');
$app->post('/baskets/{wrong_basket_id}/setdescription/', $bad_request_exception);
/**
* Route : /baskets/BASKET_ID/delete/FORMAT/
*
* Method : POST
*
* Parameters :
* BASKET_ID : required INT
*
*/
$route = '/baskets/{basket_id}/delete/';
$app->post(
$route, function($basket_id) use ($app)
{
$result = $app['api']->delete_basket($app['request'], $basket_id);
return $app['response']($result);
}
)->assert('basket_id', '\d+');
$app->post('/baskets/{wrong_basket_id}/delete/', $bad_request_exception);
/**
* Route : /feeds/list/FORMAT/
*
* Method : POST
*
* Parameters :
*
*/
// public function search_publications(\Symfony\Component\HttpFoundation\Request $app['request']);
$route = '/feeds/list/';
$app->get(
$route, function() use ($app)
{
$result = $app['api']->search_publications($app['request'], $app['p4user']);
return $app['response']($result);
}
);
/**
* Route : /feeds/PUBLICATION_ID/content/FORMAT/
*
* Method : GET
*
* Parameters :
* PUBLICATION_ID : required INT
*
*/
// public function get_publication(\Symfony\Component\HttpFoundation\Request $app['request'], $publication_id);
$route = '/feeds/{feed_id}/content/';
$app->get(
$route, function($feed_id) use ($app)
{
$result = $app['api']->get_publication($app['request'], $feed_id, $app['p4user']);
return $app['response']($result);
}
)->assert('feed_id', '\d+');
$app->get('/feeds/{wrong_feed_id}/content/', $bad_request_exception);
/**
* *******************************************************************
*
* Route Errors
*
*/
$app->error(function (\Exception $e) use ($app)
{
if ($e instanceof API_V1_exception_methodnotallowed)
$code = API_V1_result::ERROR_METHODNOTALLOWED;
elseif ($e instanceof Exception\MethodNotAllowedHttpException)
$code = API_V1_result::ERROR_METHODNOTALLOWED;
elseif ($e instanceof API_V1_exception_badrequest)
$code = API_V1_result::ERROR_BAD_REQUEST;
elseif ($e instanceof API_V1_exception_forbidden)
$code = API_V1_result::ERROR_FORBIDDEN;
elseif ($e instanceof API_V1_exception_unauthorized)
$code = API_V1_result::ERROR_UNAUTHORIZED;
elseif ($e instanceof API_V1_exception_internalservererror)
$code = API_V1_result::ERROR_INTERNALSERVERERROR;
// elseif ($e instanceof API_V1_exception_notfound)
// $code = API_V1_result::ERROR_NOTFOUND;
elseif ($e instanceof Exception_NotFound)
$code = API_V1_result::ERROR_NOTFOUND;
elseif ($e instanceof Exception\NotFoundHttpException)
$code = API_V1_result::ERROR_NOTFOUND;
else
$code = API_V1_result::ERROR_INTERNALSERVERERROR;
$result = $app['api']->get_error_message($app['request'], $code);
return $app['response']($result);
});
//// public function get_version();
////
////
//// /**
//// * Route : /records/DATABOX_ID/RECORD_ID/addtobasket/FORMAT/
//// *
//// * Method : POST
//// *
//// * Parameters :
//// * DATABOX_ID : required INT
//// * RECORD_ID : required INT
//// *
//// */
//// public function add_record_tobasket(\Symfony\Component\HttpFoundation\Request $app['request'], $databox_id, $record_id);
////
////
//// /**
//// * Route : /feeds/PUBLICATION_ID/remove/FORMAT/
//// *
//// * Method : GET
//// *
//// * Parameters :
//// * PUBLICATION_ID : required INT
//// *
//// */
//// public function remove_publications(\Symfony\Component\HttpFoundation\Request $app['request'], $publication_id);
////
////
//// /**
//// * Route : /users/search/FORMAT/
//// *
//// * Method : POST-GET
//// *
//// * Parameters :
//// *
//// */
//// public function search_users(\Symfony\Component\HttpFoundation\Request $app['request']);
////
//// /**
//// * Route : /users/USER_ID/access/FORMAT/
//// *
//// * Method : GET
//// *
//// * Parameters :
//// * USER_ID : required INT
//// *
//// */
//// public function get_user_acces(\Symfony\Component\HttpFoundation\Request $app['request'], $usr_id);
////
//// /**
//// * Route : /users/add/FORMAT/
//// *
//// * Method : POST
//// *
//// * Parameters :
//// *
//// */
//// public function add_user(\Symfony\Component\HttpFoundation\Request $app['request']);
return $app;
});

View File

@@ -37,9 +37,9 @@ class module_console_aboutAuthors extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(file_get_contents(dirname(__FILE__) . '/../../../../AUTHORS'));
$output->writeln(file_get_contents(__DIR__ . '/../../../../AUTHORS'));
return;
return 0;
}
}

View File

@@ -37,9 +37,9 @@ class module_console_aboutLicense extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(file_get_contents(dirname(__FILE__) . '/../../../../LICENSE'));
$output->writeln(file_get_contents(__DIR__ . '/../../../../LICENSE'));
return;
return 0;
}
}

View File

@@ -0,0 +1,248 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_checkExtension extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Delete a documentation field from a Databox');
$this->addOption('usr_id', 'u', InputOption::VALUE_OPTIONAL, 'Usr_id to use. If no user, get the first available');
$this->addOption('query', '', InputOption::VALUE_OPTIONAL, 'The query', 'last');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
if (!extension_loaded('phrasea2'))
printf("Missing Extension php-phrasea");
$appbox = \appbox::get_instance();
$registry = $appbox->get_registry();
$usr_id = $input->getOption('usr_id');
try
{
$TestUser = \User_Adapter::getInstance($usr_id, $appbox);
}
catch (\Exception $e)
{
$output->writeln("<error>Wrong user !</error>");
return 1;
}
$output->writeln(
sprintf(
"\nWill do the check with user <info>%s</info> (%s)\n"
, $TestUser->get_display_name()
, $TestUser->get_email()
)
);
$output->writeln("PHRASEA FUNCTIONS");
foreach (get_extension_funcs("phrasea2") as $function)
{
$output->writeln("<info>$function</info>");
}
require (__DIR__ . '/../../../../config/connexion.inc');
$output->writeln("\n-- phrasea_conn --");
if (phrasea_conn($hostname, $port, $user, $password, $dbname) !== true)
{
$output->writeln("<error>Failed ! </error> got no connection");
return 1;
}
else
{
$output->writeln("<info>Succes ! </info> got connection");
}
$output->writeln("");
$output->writeln("\n-- phrasea_info --");
foreach (phrasea_info() as $key => $value)
{
$output->writeln("\t$key => $value");
}
$output->writeln("");
$output->writeln("\n-- phrasea_create_session --");
$sessid = phrasea_create_session((string) $TestUser->get_id());
if (ctype_digit((string) $sessid))
{
$output->writeln("<info>Succes ! </info> got session id $sessid");
}
else
{
$output->writeln("<error>Failed ! </error> got no session id");
return 1;
}
$output->writeln("\n-- phrasea_open_session --");
$ph_session = phrasea_open_session($sessid, $usr_id);
if ($ph_session)
{
$output->writeln("<info>Succes ! </info> got session ");
}
else
{
$output->writeln("<error>Failed ! </error> got no session ");
return 1;
}
$output->writeln("\n-- phrasea_clear_cache --");
$ret = phrasea_clear_cache($sessid);
if ($sessid)
{
$output->writeln("<info>Succes ! </info> got session ");
}
else
{
$output->writeln("<error>Failed ! </error> got no session ");
return 1;
}
$tbases = array();
foreach ($ph_session["bases"] as $phbase)
{
$tcoll = array();
foreach ($phbase["collections"] as $coll)
{
$tcoll[] = 0 + $coll["base_id"];
}
if (sizeof($tcoll) > 0)
{
$kbase = "S" . $phbase["sbas_id"];
$tbases[$kbase] = array();
$tbases[$kbase]["sbas_id"] = $phbase["sbas_id"];
$tbases[$kbase]["searchcoll"] = $tcoll;
$tbases[$kbase]["mask_xor"] = $tbases[$kbase]["mask_and"] = 0;
$qp = new searchEngine_adapter_phrasea_queryParser();
$treeq = $qp->parsequery($input->getOption('query'));
$arrayq = $qp->makequery($treeq);
$tbases[$kbase]["arrayq"] = $arrayq;
}
}
$output->writeln("\n-- phrasea_query --");
$nbanswers = 0;
foreach ($tbases as $kb => $base)
{
$tbases[$kb]["results"] = NULL;
$ret = phrasea_query2(
$ph_session["session_id"]
, $base["sbas_id"]
, $base["searchcoll"]
, $base["arrayq"]
, $registry->get('GV_sit')
, $usr_id
, FALSE
, PHRASEA_MULTIDOC_DOCONLY
);
if ($ret)
{
$output->writeln("<info>Succes ! </info> got result on sbas_id " . $base["sbas_id"]);
}
else
{
$output->writeln("<error>Failed ! </error> No results on sbas_id " . $base["sbas_id"]);
return 1;
}
$tbases[$kb]["results"] = $ret;
$nbanswers += $tbases[$kb]["results"]["nbanswers"];
}
$output->writeln("Got a total of <info>$nbanswers</info> answers");
$output->writeln("\n-- phrasea_fetch_results --");
$rs = phrasea_fetch_results($sessid, $usr_id, 1, true, '[[em]]', '[[/em]]');
if ($rs)
{
$output->writeln("<info>Succes ! </info> got result ");
}
else
{
$output->writeln("<error>Failed ! </error> got no result ");
return 1;
}
$output->writeln("\n-- phrasea_close_session --");
$rs = phrasea_close_session($sessid);
if ($rs)
{
$output->writeln("<info>Succes ! </info> closed ! ");
}
else
{
$output->writeln("<error>Failed ! </error> not closed ");
return 1;
}
return 0;
}
}

View File

@@ -0,0 +1,98 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_fieldsDelete extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Delete a documentation field from a Databox');
$this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
$this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
if (!$input->getOption('sbas_id'))
throw new \Exception('Missing argument sbas_id');
if (!$input->getOption('meta_struct_id'))
throw new \Exception('Missing argument meta_struct_id');
try
{
$databox = \databox::get_instance((int) $input->getOption('sbas_id'));
}
catch (\Exception $e)
{
$output->writeln("<error>Invalid databox id </error>");
return 1;
}
try
{
$field = $databox->get_meta_structure()->get_element((int) $input->getOption('meta_struct_id'));
}
catch (\Exception $e)
{
$output->writeln("<error>Invalid meta struct id </error>");
return 1;
}
$dialog = $this->getHelperSet()->get('dialog');
$continue = mb_strtolower(
$dialog->ask(
$output
, "<question>About to delete " . $field->get_name() . " (y/N)</question>"
, 'n'
)
);
if($continue != 'y')
{
$output->writeln("Request canceled by user");
return 1;
}
$output->writeln("Deleting ... ");
$field->delete();
$output->writeln("Done with success !");
return 0;
}
}

View File

@@ -0,0 +1,70 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_fieldsList extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('List all databox fields');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$appbox = \appbox::get_instance(\bootstrap::getCore());
foreach ($appbox->get_databoxes() as $databox)
{
/* @var $databox \databox */
$output->writeln(
sprintf(
"\n ---------------- \nOn databox %s (sbas_id %d) :\n"
, $databox->get_viewname()
, $databox->get_sbas_id()
)
);
foreach ($databox->get_meta_structure()->get_elements() as $field)
{
$output->writeln(
sprintf(
" %2d - <info>%s</info> (%s) %s"
, $field->get_id()
, $field->get_name()
, $field->get_type()
, ($field->is_multi() ? '<comment>multi</comment>' : '')
)
);
}
}
return 0;
}
}

View File

@@ -0,0 +1,284 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_fieldsMerge extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Merge databox structure fields');
$this->addOption(
'source'
, 'f'
, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
, 'Metadata structure ids for source'
, array()
);
$this->addOption(
'destination'
, 'd'
, InputOption::VALUE_REQUIRED
, 'Metadata structure id destination'
);
$this->addOption(
'sbas_id'
, 's'
, InputOption::VALUE_REQUIRED
, 'Databox sbas_id'
);
$this->addOption(
'separator'
, ''
, InputOption::VALUE_OPTIONAL
, 'Separator for concatenation (if destination is monovalued)'
, ';'
);
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("");
if (!$input->getOption('sbas_id'))
throw new \Exception('Missing argument sbas_id');
try
{
$databox = \databox::get_instance((int) $input->getOption('sbas_id'));
}
catch (\Exception $e)
{
$output->writeln("<error>Invalid databox id </error>");
return 1;
}
$sources = array();
foreach ($input->getOption('source') as $source_id)
{
$sources[] = $databox->get_meta_structure()->get_element($source_id);
}
if (count($sources) === 0)
throw new \Exception('No sources to proceed');
if (!$input->getOption('destination'))
throw new \Exception('Missing argument destination');
$separator = ' ' . $input->getOption('separator') . ' ';
$destination = $databox->get_meta_structure()->get_element($input->getOption('destination'));
$types = $multis = array();
foreach ($sources as $source)
{
array_push($types, $source->get_type());
array_push($multis, $source->is_multi());
}
$types = array_unique($types);
$multis = array_unique($multis);
if (count(array_unique($types)) > 1)
{
$output->writeln(
sprintf("Warning, trying to merge inconsistent types : <comment>%s</comment>\n"
, implode(', ', $types)
)
);
}
if (count(array_unique($multis)) > 1)
{
$output->writeln(
sprintf(
"Warning, trying to merge <comment>mono and multi</comment> values fields\n"
)
);
}
$field_names = array();
foreach ($sources as $source)
{
$field_names[] = $source->get_name();
}
if (count($multis) == 1)
{
if ($multis[0] === false && !$destination->is_multi())
{
$output->writeln(
sprintf(
"You are going to merge <info>mono valued fields</info> in a "
. "<info>monovalued field</info>, fields will be "
. "<comment>concatenated</comment> in the following order : %s"
, implode($separator, $field_names)
)
);
$this->displayHelpConcatenation($output);
}
elseif ($multis[0] === true && !$destination->is_multi())
{
$output->writeln(
sprintf(
"You are going to merge <info>multi valued</info> fields in a "
. "<info>monovalued field</info>, fields will be "
. "<comment>concatenated</comment> in the following order : %s"
, implode(' ', $field_names)
)
);
$this->displayHelpConcatenation($output);
}
elseif ($multis[0] === false && $destination->is_multi())
{
$output->writeln(
sprintf(
"You are going to merge <info>mono valued fields</info> in a "
. "<info>multivalued field</info>"
)
);
}
elseif ($multis[0] === true && $destination->is_multi())
{
$output->writeln(
sprintf(
"You are going to merge <info>multi valued fields</info> in a "
. "<info>multivalued field</info>"
)
);
}
}
elseif ($destination->is_multi())
{
$output->writeln(
sprintf(
"You are going to merge <info>mixed valued</info> fields in a "
. "<info>multivalued</info> field"
)
);
}
else
{
$output->writeln(
sprintf(
"You are going to merge <info>mixed valued</info> fields in a "
. "<info>monovalued field</info>, fields will be "
. "<comment>concatenated</comment> in the following order : %s"
, implode($separator, $field_names)
)
);
$this->displayHelpConcatenation($output);
}
$start = 0;
$quantity = 100;
do
{
$sql = 'SELECT record_id FROM record
ORDER BY record_id LIMIT ' . $start . ', ' . $quantity;
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($results as $row)
{
$record = $databox->get_record($row['record_id']);
$datas = array();
foreach ($sources as $source)
{
try
{
$value = $record->get_caption()->get_field($source->get_name())->get_value();
}
catch (\Exception $e)
{
$value = array();
}
if (!is_array($value))
{
$value = array($value);
}
$datas = array_merge($datas, $value);
}
$datas = array_unique($datas);
if (!$destination->is_multi())
{
$datas = array(implode($separator, $datas));
}
try
{
$record->get_caption()->get_field($destination->get_name())->set_value($datas);
}
catch (\Exception $e)
{
$record->set_metadatas(
array(
array(
'meta_struct_id' => $destination->get_id()
, 'meta_id' => null
, 'value' => $datas
)
)
, true
);
}
unset($record);
}
$start += $quantity;
}
while (count($results) > 0);
return 0;
}
protected function displayHelpConcatenation(OutputInterface $output)
{
$output->writeln("\nYou can choose the concatenation order in the "
. "commandline (first option is first value) and set a separator "
. "with the --separator option)");
return $this;
}
}

View File

@@ -0,0 +1,106 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_fieldsRename extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Rename a documentation field from a Databox');
$this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
$this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
$this->addOption('name', 'n', InputOption::VALUE_REQUIRED, 'The new name');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
if (!$input->getOption('sbas_id'))
throw new \Exception('Missing argument sbas_id');
if (!$input->getOption('meta_struct_id'))
throw new \Exception('Missing argument meta_struct_id');
if (!$input->getOption('name'))
throw new \Exception('Missing argument name');
$new_name = $input->getOption('name');
try
{
$databox = \databox::get_instance((int) $input->getOption('sbas_id'));
}
catch (\Exception $e)
{
$output->writeln("<error>Invalid databox id </error>");
return 1;
}
try
{
$field = $databox->get_meta_structure()->get_element((int) $input->getArgument('meta_struct_id'));
}
catch (\Exception $e)
{
$output->writeln("<error>Invalid meta struct id </error>");
return 1;
}
$dialog = $this->getHelperSet()->get('dialog');
$continue = mb_strtolower(
$dialog->ask(
$output
, "<question>About to rename " . $field->get_name() . " into ".$new_name." (y/N)</question>"
, 'n'
)
);
if($continue != 'y')
{
$output->writeln("Request canceled by user");
return 1;
}
$output->writeln("Renaming ... ");
$field->set_name($new_name);
$field->save();
$output->writeln("Done with success !");
return 0;
}
}

View File

@@ -0,0 +1,922 @@
<?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.
*/
use Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Console\Command\Command;
use Alchemy\Phrasea\Core;
use Symfony\Component\Yaml;
/**
* @todo write tests
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_console_fileEnsureDevSetting extends Command
{
const ALERT = 1;
const ERROR = 0;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration
*/
protected $configuration;
protected $testSuite = array(
'checkPhraseanetScope'
, 'checkDatabaseScope'
, 'checkTeamplateEngineService'
, 'checkOrmService'
, 'checkCacheService'
, 'checkOpcodeCacheService'
);
protected $errors = 0;
protected $alerts = 0;
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Ensure development settings');
$this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
$this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
$environnement = $input->getArgument('conf');
$this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
if (!$this->configuration->isInstalled())
{
$output->writeln(sprintf("\nPhraseanet is not installed\n"));
}
$this->checkParse($output);
$output->writeln(sprintf("Will Ensure Production Settings on <info>%s</info>", $this->configuration->getEnvironnement()));
$this->runTests($output);
$retval = $this->errors;
if ($input->getOption('strict'))
{
$retval += $this->alerts;
}
if ($retval > 0)
{
$output->writeln("\n<error>Some errors found in your conf</error>");
}
else
{
$output->writeln("\n<info>Your dev settings are setted correctly ! Enjoy</info>");
}
$output->writeln('End');
return $retval;
}
private function runTests(OutputInterface $output)
{
foreach ($this->testSuite as $test)
{
$display = "";
switch ($test)
{
case 'checkPhraseanetScope' :
$display = "Phraseanet Configuration";
break;
case 'checkDatabaseScope' :
$display = "Database";
break;
case 'checkTeamplateEngineService' :
$display = "Template Engine";
break;
case 'checkOrmService' :
$display = "ORM";
break;
case 'checkCacheService' :
$display = "Cache";
break;
case 'checkOpcodeCacheService' :
$display = "Opcode";
break;
default:
throw new \Exception('Unknown test');
break;
}
$output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
call_user_func(array($this, $test), $output);
}
}
private function checkParse(OutputInterface $output)
{
if (!$this->configuration->getConfigurations())
{
throw new \Exception("Unable to load configurations\n");
}
if (!$this->configuration->getConnexions())
{
throw new \Exception("Unable to load connexions\n");
}
if (!$this->configuration->getServices())
{
throw new \Exception("Unable to load services\n");
}
return;
}
private function checkCacheService(OutputInterface $output)
{
$cache = $this->configuration->getCache();
if ($this->probeCacheService($output, $cache))
{
if ($this->recommendedCacheService($output, $cache, true))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<comment>Cache server recommended</comment>';
$this->alerts++;
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", 'MainCache', $work_message);
$this->printConf($output, "\t" . 'service', $cache, false, $verification);
$this->verifyCacheOptions($output, $cache);
}
private function checkOpcodeCacheService(OutputInterface $output)
{
$cache = $this->configuration->getOpcodeCache();
if ($this->probeCacheService($output, $cache))
{
if ($this->recommendedCacheService($output, $cache, false))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<error>No cache required</error>';
$this->errors++;
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", 'OpcodeCache', $work_message);
$this->printConf($output, "\t" . 'service', $cache, false, $verification);
$this->verifyCacheOptions($output, $cache);
}
private function checkPhraseanetScope(OutputInterface $output)
{
$required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
$phraseanet = $this->configuration->getPhraseanet();
foreach ($phraseanet->all() as $conf => $value)
{
switch ($conf)
{
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'servername':
$url = $value;
$required = array_diff($required, array($conf));
$parseUrl = parse_url($url);
if (empty($url))
{
$message = "<error>should not be empty</error>";
$this->errors++;
}
elseif ($url == 'http://sub.domain.tld/')
{
$this->alerts++;
$message = "<comment>may be wrong</comment>";
}
elseif (!filter_var($url, FILTER_VALIDATE_URL))
{
$message = "<error>not valid</error>";
$this->errors++;
}
else
{
$message = "<info>OK</info>";
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'maintenance':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false)
{
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'debug':
case 'display_errors':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true)
{
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'database':
$required = array_diff($required, array($conf));
try
{
$service = $this->configuration->getConnexion($value);
if ($this->verifyDatabaseConnexion($service))
{
$message = '<info>OK</info>';
}
else
{
$message = '<error>Connection not available</error>';
$this->errors++;
}
}
catch (\Exception $e)
{
$message = '<error>Unknown connection</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
private function checkDatabaseScope(OutputInterface $output)
{
$connexionName = $this->configuration->getPhraseanet()->get('database');
$connexion = $this->configuration->getConnexion($connexionName);
try
{
if ($this->verifyDatabaseConnexion($connexion))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify connection <info>%s</info> : %s", $connexionName, $work_message));
$required = array('driver');
if (!$connexion->has('driver'))
{
$output->writeln("\n<error>Connection has no driver</error>");
$this->errors++;
}
elseif ($connexion->get('driver') == 'pdo_mysql')
{
$required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
}
elseif ($connexion->get('driver') == 'pdo_sqlite')
{
$required = array('driver', 'path', 'charset');
}
else
{
$output->writeln("\n<error>Your driver is not managed</error>");
$this->errors++;
}
foreach ($connexion->all() as $conf => $value)
{
switch ($conf)
{
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'charset':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'UTF8')
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'path':
$required = array_diff($required, array($conf));
$message = is_writable(dirname($value)) ? '<info>OK</info>' : '<error>Not writeable</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbname':
case 'user':
case 'host':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'port':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value))
{
$message = '<error>Should be ctype_digit</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'password':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$value = '***********';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'driver':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'pdo_mysql')
{
$message = '<error>MySQL recommended</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
{
try
{
$config = new \Doctrine\DBAL\Configuration();
$conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
return true;
}
catch (\Exception $e)
{
}
return false;
}
private function checkTeamplateEngineService(OutputInterface $output)
{
$templateEngineName = $this->configuration->getTemplating();
$configuration = $this->configuration->getService($templateEngineName);
try
{
Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
$work_message = '<info>Works !</info>';
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not load template engine !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Template engine <info>%s</info> : %s", $templateEngineName, $work_message));
if (!$configuration->has('type'))
{
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
}
elseif ($configuration->get('type') == 'TemplateEngine\\Twig')
{
$required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
}
else
{
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value)
{
switch ($conf)
{
case 'type':
$message = '<info>OK</info>';
if ($value !== 'TemplateEngine\\Twig')
{
$message = '<error>Not recognized</error>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value)
{
switch ($conf)
{
case 'debug';
case 'strict_variables';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true)
{
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'autoescape';
case 'optimizer';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true)
{
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'charset';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'utf-8')
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
private function checkOrmService(OutputInterface $output)
{
$ormName = $this->configuration->getOrm();
$configuration = $this->configuration->getService($ormName);
try
{
$service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
$work_message = '<info>Works !</info>';
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify ORM engine <info>%s</info> : %s", $ormName, $work_message));
if (!$configuration->has('type'))
{
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
}
elseif ($configuration->get('type') == 'Orm\\Doctrine')
{
$required = array('debug', 'dbal', 'cache');
}
else
{
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value)
{
switch ($conf)
{
case 'type':
$message = $value == 'Orm\\Doctrine' ? '<info>OK</info>' : '<error>Not recognized</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value)
{
switch ($conf)
{
case 'log':
$message = '<info>OK</info>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'cache':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be Array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
$required_caches = array('query', 'result', 'metadata');
foreach ($value as $name => $cache_type)
{
$required_caches = array_diff($required_caches, array($name));
foreach ($cache_type as $key_cache => $value_cache)
{
switch ($key_cache)
{
case 'service':
if ($this->probeCacheService($output, $value_cache))
{
$server = $name === 'result';
if ($this->recommendedCacheService($output, $value_cache, $server))
{
$work_message = '<info>Works !</info>';
}
else
{
$this->errors++;
$work_message = '<error>No cache required</error>';
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", $name, $work_message);
$this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
$this->verifyCacheOptions($output, $value_cache);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $key_cache, $value_cache, false, '<comment>Not recognized</comment>');
break;
}
if (!isset($cache_type['service']))
{
$output->writeln('<error>Miss service for %s</error>', $cache_type);
$this->errors++;
}
}
}
if (count($required_caches) > 0)
{
$output->writeln(sprintf('<error>Miss required caches %s</error>', implode(', ', $required_caches)));
$this->errors++;
}
break;
case 'debug':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true)
{
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbal':
$required = array_diff($required, array($conf));
try
{
$connexion = $this->configuration->getConnexion($value);
$this->verifyDatabaseConnexion($connexion);
$message = '<info>OK</info>';
}
catch (\Exception $e)
{
$message = '<error>Failed</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
{
try
{
$conf = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $conf
);
}
catch (\Exception $e)
{
return false;
}
$required_options = array();
switch ($Service->getType())
{
default:
break;
case 'memcache':
$required_options = array('host', 'port');
break;
}
if ($required_options)
{
foreach ($conf->get('options') as $conf => $value)
{
switch ($conf)
{
case 'host';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
case 'port';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value))
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
}
if (count($required_options) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required_options)));
$this->errors++;
}
}
protected function probeCacheService(OutputInterface $output, $ServiceName)
{
try
{
$originalConfiguration = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $originalConfiguration
);
}
catch (\Exception $e)
{
return false;
}
if ($Service->getDriver()->isServer())
{
switch ($Service->getType())
{
default:
return false;
break;
case 'memcache':
if (!@memcache_connect($Service->getHost(), $Service->getPort()))
{
return false;
}
break;
}
}
return true;
}
protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
{
try
{
$originalConfiguration = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $originalConfiguration
);
}
catch (\Exception $e)
{
return false;
}
return $Service->getType() === 'array';
}
private function printConf($output, $scope, $value, $scopage = false, $message = '')
{
if (is_array($value))
{
foreach ($value as $key => $val)
{
if ($scopage)
$key = $scope . ":" . $key;
$this->printConf($output, $key, $val, $scopage, '');
}
}
elseif (is_bool($value))
{
if ($value === false)
{
$value = 'false';
}
elseif ($value === true)
{
$value = 'true';
}
$output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
}
elseif (!empty($value))
{
$output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
}
}
}

View File

@@ -0,0 +1,934 @@
<?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.
*/
use Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Console\Command\Command;
use Alchemy\Phrasea\Core;
use Symfony\Component\Yaml;
/**
* @todo write tests
*
* @package
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_console_fileEnsureProductionSetting extends Command
{
const ALERT = 1;
const ERROR = 0;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration
*/
protected $configuration;
protected $testSuite = array(
'checkPhraseanetScope'
, 'checkDatabaseScope'
, 'checkTeamplateEngineService'
, 'checkOrmService'
, 'checkCacheService'
, 'checkOpcodeCacheService'
);
protected $errors = 0;
protected $alerts = 0;
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Ensure production settings');
$this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
$this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
$environnement = $input->getArgument('conf');
$this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
if (!$this->configuration->isInstalled())
{
$output->writeln(sprintf("\nPhraseanet is not installed\n"));
}
$this->checkParse($output);
$output->writeln(sprintf("Will Ensure Production Settings on <info>%s</info>", $this->configuration->getEnvironnement()));
$this->runTests($output);
$retval = $this->errors;
if ($input->getOption('strict'))
{
$retval += $this->alerts;
}
if ($retval > 0)
{
$output->writeln("\n<error>Some errors found in your conf</error>");
}
else
{
$output->writeln("\n<info>Your production settings are setted correctly ! Enjoy</info>");
}
$output->writeln('End');
return $retval;
}
private function runTests(OutputInterface $output)
{
foreach ($this->testSuite as $test)
{
$display = "";
switch ($test)
{
case 'checkPhraseanetScope' :
$display = "Phraseanet Configuration";
break;
case 'checkDatabaseScope' :
$display = "Database";
break;
case 'checkTeamplateEngineService' :
$display = "Template Engine";
break;
case 'checkOrmService' :
$display = "ORM";
break;
case 'checkCacheService' :
$display = "Cache";
break;
case 'checkOpcodeCacheService' :
$display = "Opcode";
break;
default:
throw new \Exception('Unknown test');
break;
}
$output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
call_user_func(array($this, $test), $output);
}
}
private function checkParse(OutputInterface $output)
{
if (!$this->configuration->getConfigurations())
{
throw new \Exception("Unable to load configurations\n");
}
if (!$this->configuration->getConnexions())
{
throw new \Exception("Unable to load connexions\n");
}
if (!$this->configuration->getServices())
{
throw new \Exception("Unable to load services\n");
}
return;
}
private function checkCacheService(OutputInterface $output)
{
$cache = $this->configuration->getCache();
if ($this->probeCacheService($output, $cache))
{
if ($this->recommendedCacheService($output, $cache, true))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<comment>Cache server recommended</comment>';
$this->alerts++;
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", 'MainCache', $work_message);
$this->printConf($output, "\t" . 'service', $cache, false, $verification);
$this->verifyCacheOptions($output, $cache);
}
private function checkOpcodeCacheService(OutputInterface $output)
{
$cache = $this->configuration->getOpcodeCache();
if ($this->probeCacheService($output, $cache))
{
if ($this->recommendedCacheService($output, $cache, false))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<comment>Opcode recommended</comment>';
$this->alerts++;
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", 'OpcodeCache', $work_message);
$this->printConf($output, "\t" . 'service', $cache, false, $verification);
$this->verifyCacheOptions($output, $cache);
}
private function checkPhraseanetScope(OutputInterface $output)
{
$required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
$phraseanet = $this->configuration->getPhraseanet();
foreach ($phraseanet->all() as $conf => $value)
{
switch ($conf)
{
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'servername':
$url = $value;
$required = array_diff($required, array($conf));
$parseUrl = parse_url($url);
if (empty($url))
{
$message = "<error>should not be empty</error>";
$this->errors++;
}
elseif ($url == 'http://sub.domain.tld/')
{
$this->alerts++;
$message = "<comment>may be wrong</comment>";
}
elseif (!filter_var($url, FILTER_VALIDATE_URL))
{
$message = "<error>not valid</error>";
$this->errors++;
}
elseif ($parseUrl["scheme"] !== "https")
{
$this->alerts++;
$message = "<comment>should be https</comment>";
}
else
{
$message = "<info>OK</info>";
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'maintenance':
case 'debug':
case 'display_errors':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false)
{
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'database':
$required = array_diff($required, array($conf));
try
{
$service = $this->configuration->getConnexion($value);
if ($this->verifyDatabaseConnexion($service))
{
$message = '<info>OK</info>';
}
else
{
$message = '<error>Connection not available</error>';
$this->errors++;
}
}
catch (\Exception $e)
{
$message = '<error>Unknown connection</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
private function checkDatabaseScope(OutputInterface $output)
{
$connexionName = $this->configuration->getPhraseanet()->get('database');
$connexion = $this->configuration->getConnexion($connexionName);
try
{
if ($this->verifyDatabaseConnexion($connexion))
{
$work_message = '<info>Works !</info>';
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify connection <info>%s</info> : %s", $connexionName, $work_message));
$required = array('driver');
if (!$connexion->has('driver'))
{
$output->writeln("\n<error>Connection has no driver</error>");
$this->errors++;
}
elseif ($connexion->get('driver') == 'pdo_mysql')
{
$required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
}
elseif ($connexion->get('driver') == 'pdo_sqlite')
{
$required = array('driver', 'path', 'charset');
}
else
{
$output->writeln("\n<error>Your driver is not managed</error>");
$this->errors++;
}
foreach ($connexion->all() as $conf => $value)
{
switch ($conf)
{
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'charset':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'UTF8')
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'path':
$required = array_diff($required, array($conf));
$message = is_writable(dirname($value)) ? '<info>OK</info>' : '<error>Not writeable</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbname':
case 'user':
case 'host':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'port':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value))
{
$message = '<error>Should be ctype_digit</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'password':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$value = '***********';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'driver':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'pdo_mysql')
{
$message = '<error>MySQL recommended</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
{
try
{
$config = new \Doctrine\DBAL\Configuration();
$conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
return true;
}
catch (\Exception $e)
{
}
return false;
}
private function checkTeamplateEngineService(OutputInterface $output)
{
$templateEngineName = $this->configuration->getTemplating();
$configuration = $this->configuration->getService($templateEngineName);
try
{
Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
$work_message = '<info>Works !</info>';
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not load template engine !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Template engine <info>%s</info> : %s", $templateEngineName, $work_message));
if (!$configuration->has('type'))
{
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
}
elseif ($configuration->get('type') == 'TemplateEngine\\Twig')
{
$required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
}
else
{
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value)
{
switch ($conf)
{
case 'type':
$message = '<info>OK</info>';
if($value !== 'TemplateEngine\\Twig')
{
$message = '<error>Not recognized</error>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value)
{
switch ($conf)
{
case 'debug';
case 'strict_variables';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false)
{
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'autoescape';
case 'optimizer';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true)
{
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'charset';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'utf-8')
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
private function checkOrmService(OutputInterface $output)
{
$ormName = $this->configuration->getOrm();
$configuration = $this->configuration->getService($ormName);
try
{
$service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
$work_message = '<info>Works !</info>';
}
catch (\Exception $e)
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify ORM engine <info>%s</info> : %s", $ormName, $work_message));
if (!$configuration->has('type'))
{
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
}
elseif ($configuration->get('type') == 'Orm\\Doctrine')
{
$required = array('debug', 'dbal', 'cache');
}
else
{
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value)
{
switch ($conf)
{
case 'type':
$message = $value == 'Orm\\Doctrine' ? '<info>OK</info>' : '<error>Not recognized</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value)
{
switch ($conf)
{
case 'log':
$message = '<info>OK</info>';
if ($value !== false)
{
$message = '<error>Should be deactivated</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'cache':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_array($value))
{
$message = '<error>Should be Array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
$required_caches = array('query', 'result', 'metadata');
foreach ($value as $name => $cache_type)
{
$required_caches = array_diff($required_caches, array($name));
foreach ($cache_type as $key_cache => $value_cache)
{
switch ($key_cache)
{
case 'service':
if ($this->probeCacheService($output, $value_cache))
{
$server = $name === 'result';
if ($this->recommendedCacheService($output, $value_cache, $server))
{
$work_message = '<info>Works !</info>';
}
else
{
$this->alerts++;
if ($server)
{
$work_message = '<comment>Cache server recommended</comment>';
}
else
{
$work_message = '<comment>Opcode cache recommended</comment>';
}
}
}
else
{
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %s", $name, $work_message);
$this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
$this->verifyCacheOptions($output, $value_cache);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $key_cache, $value_cache, false, '<comment>Not recognized</comment>');
break;
}
if (!isset($cache_type['service']))
{
$output->writeln('<error>Miss service for %s</error>', $cache_type);
$this->errors++;
}
}
}
if (count($required_caches) > 0)
{
$output->writeln(sprintf('<error>Miss required caches %s</error>', implode(', ', $required_caches)));
$this->errors++;
}
break;
case 'debug':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false)
{
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbal':
$required = array_diff($required, array($conf));
try
{
$connexion = $this->configuration->getConnexion($value);
$this->verifyDatabaseConnexion($connexion);
$message = '<info>OK</info>';
}
catch (\Exception $e)
{
$message = '<error>Failed</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required)));
$this->errors++;
}
return;
}
protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
{
try
{
$conf = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $conf
);
}
catch (\Exception $e)
{
return false;
}
$required_options = array();
switch ($Service->getType())
{
default:
break;
case 'memcache':
$required_options = array('host', 'port');
break;
}
if ($required_options)
{
foreach ($conf->get('options') as $conf => $value)
{
switch ($conf)
{
case 'host';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value))
{
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
case 'port';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value))
{
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
}
if (count($required_options) > 0)
{
$output->writeln(sprintf('<error>Miss required keys %s</error>', implode(', ', $required_options)));
$this->errors++;
}
}
protected function probeCacheService(OutputInterface $output, $ServiceName)
{
try
{
$originalConfiguration = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $originalConfiguration
);
}
catch (\Exception $e)
{
return false;
}
if ($Service->getDriver()->isServer())
{
switch ($Service->getType())
{
default:
return false;
break;
case 'memcache':
if (!@memcache_connect($Service->getHost(), $Service->getPort()))
{
return false;
}
break;
}
}
return true;
}
protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
{
try
{
$originalConfiguration = $this->configuration->getService($ServiceName);
$Service = Core\Service\Builder::create(
\bootstrap::getCore(), $originalConfiguration
);
}
catch (\Exception $e)
{
return false;
}
if ($Service->getType() === 'array')
{
return false;
}
return $server === $Service->getDriver()->isServer();
}
private function printConf($output, $scope, $value, $scopage = false, $message = '')
{
if (is_array($value))
{
foreach ($value as $key => $val)
{
if ($scopage)
$key = $scope . ":" . $key;
$this->printConf($output, $key, $val, $scopage, '');
}
}
elseif (is_bool($value))
{
if ($value === false)
{
$value = 'false';
}
elseif ($value === true)
{
$value = 'true';
}
$output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
}
elseif (!empty($value))
{
$output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* This file is part of Phraseanet
*
@@ -54,17 +55,27 @@ class module_console_schedulerStart extends Command
public function execute(InputInterface $zinput, OutputInterface $output)
{
if(!setup::is_installed())
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Phraseanet is not set up');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$scheduler = new task_Scheduler();
$scheduler->run($zinput, $output); //, !$input->getOption('nolog'), !$input->getOption('notasklog'));
return;
try
{
$scheduler = new task_Scheduler();
$scheduler->run($output, true);
}
catch (\Exception $e)
{
return 1;
}
}
}

View File

@@ -24,6 +24,7 @@ use Symfony\Component\Console\Command\Command;
class module_console_schedulerState extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
@@ -35,26 +36,39 @@ class module_console_schedulerState extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
if(!setup::is_installed())
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Phraseanet is not set up');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$appbox = appbox::get_instance();
$task_manager = new task_manager($appbox);
try
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$task_manager = new task_manager($appbox);
$state = $task_manager->get_scheduler_state();
if ($state['schedstatus'] == 'started')
{
$output->writeln(sprintf(
'Scheduler is %s on pid %d'
, $state['schedstatus']
, $state['schedpid']
));
}
else
{
$output->writeln(sprintf('Scheduler is %s', $state['schedstatus']));
}
$state = $task_manager->get_scheduler_state();
if ($state['schedstatus'] == 'started')
$output->writeln(sprintf(
'Scheduler is %s on pid %d'
, $state['schedstatus']
, $state['schedpid']
));
else
$output->writeln(sprintf('Scheduler is %s', $state['schedstatus']));
return 0;
}
catch(\Exception $e)
{
return 1;
}
return;
}

View File

@@ -33,19 +33,30 @@ class module_console_schedulerStop extends Command
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
if(!setup::is_installed())
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Phraseanet is not set up');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$appbox = appbox::get_instance();
$task_manager = new task_manager($appbox);
try
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$task_manager = new task_manager($appbox);
$task_manager->set_sched_status(task_manager::STATUS_SCHED_TOSTOP);
$task_manager->set_sched_status(task_manager::STATUS_SCHED_TOSTOP);
return 0;
}
catch (\Exception $e)
{
return 1;
}
return;
}

View File

@@ -0,0 +1,162 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_sphinxGenerateSuggestion extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Generate suggestions for Sphinx Search Engine');
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
define('FREQ_THRESHOLD', 10);
define('SUGGEST_DEBUG', 0);
$appbox = \appbox::get_instance(\bootstrap::getCore());
$registry = $appbox->get_registry();
$params = phrasea::sbas_params();
foreach ($params as $sbas_id => $p)
{
$index = crc32(
str_replace(
array('.', '%')
, '_'
, sprintf('%s_%s_%s_%s', $p['host'], $p['port'], $p['user'], $p['dbname'])
)
);
$tmp_file = $registry->get('GV_RootPath') . 'tmp/dict' . $index . '.txt';
$databox = databox::get_instance($sbas_id);
$output->writeln("process Databox " . $databox->get_viewname() . " / $index\n");
if(!is_executable("/usr/local/bin/indexer"))
{
$output->writeln("<error>'/usr/local/bin/indexer' is not executable</error>");
return 1;
}
if(!file_exists($tmp_file))
{
$output->writeln("<error> file '".$tmp_file."' does not exist</error>");
return 1;
}
$cmd = '/usr/local/bin/indexer metadatas' . $index . ' --buildstops ' . $tmp_file . ' 1000000 --buildfreqs';
exec($cmd);
try
{
$connbas = connection::getPDOConnection($sbas_id);
}
catch (Exception $e)
{
continue;
}
$sql = 'TRUNCATE suggest';
$stmt = $connbas->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = $this->BuildDictionarySQL($output, file_get_contents($tmp_file));
if (trim($sql) !== '')
{
$stmt = $connbas->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
}
unlink($tmp_file);
}
return 0;
}
protected function BuildTrigrams($keyword)
{
$t = "__" . $keyword . "__";
$trigrams = "";
for ($i = 0; $i < strlen($t) - 2; $i++)
$trigrams .= substr($t, $i, 3) . " ";
return $trigrams;
}
protected function BuildDictionarySQL(OutputInterface $output, $in)
{
$out = '';
$n = 0;
$lines = explode("\n", $in);
foreach ($lines as $line)
{
if (trim($line) === '')
continue;
list ( $keyword, $freq ) = explode(" ", trim($line));
if ($freq < FREQ_THRESHOLD || strstr($keyword, "_") !== false || strstr($keyword, "'") !== false)
continue;
if (ctype_digit($keyword))
{
continue;
}
if (mb_strlen($keyword) < 3)
{
continue;
}
$trigrams = $this->BuildTrigrams($keyword);
if ($n++)
$out .= ",\n";
$out .= "( $n, '$keyword', '$trigrams', $freq )";
}
if (trim($out) !== '')
{
$out = "INSERT INTO suggest VALUES " . $out . ";";
}
$output->writeln(sprintf("Generated <info>%d</info> suggestions", $n));
return $out;
}
}

View File

@@ -31,7 +31,7 @@ class module_console_systemBackupDB extends Command
$dir = sprintf(
'%s/config/'
, dirname(dirname(dirname(dirname(dirname(__FILE__)))))
, dirname(dirname(dirname(dirname(__DIR__))))
);
$this->setDescription('Backup Phraseanet Databases');
@@ -45,23 +45,27 @@ class module_console_systemBackupDB extends Command
{
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Argument must be an Id.');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$output->write('Phraseanet is going to be backup...', true);
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$this->dump_base($appbox, $input, $output);
$ok = true;
$ok = $this->dump_base($appbox, $input, $output) && $ok;
foreach ($appbox->get_databoxes() as $databox)
{
$this->dump_base($databox, $input, $output);
$ok = $this->dump_base($databox, $input, $output) && $ok;
}
return;
return (int) !$ok;
}
protected function dump_base(base $base, InputInterface $input, OutputInterface $output)
@@ -91,11 +95,19 @@ class module_console_systemBackupDB extends Command
system($command);
if (file_exists($filename) && filesize($filename) > 0)
{
$output->writeln('OK');
return true;
}
else
{
$output->writeln('<error>Failed</error>');
return;
return false;
}
}
}

View File

@@ -44,10 +44,10 @@ class module_console_systemClearCache extends Command
->exclude('.git')
->exclude('.svn')
->in(array(
dirname(__FILE__) . '/../../../../tmp/cache_minify/'
, dirname(__FILE__) . '/../../../../tmp/cache_twig/'
))
;
__DIR__ . '/../../../../tmp/cache_minify/'
, __DIR__ . '/../../../../tmp/cache_twig/'
));
$count = 1;
foreach ($finder as $file)
{
@@ -59,12 +59,12 @@ class module_console_systemClearCache extends Command
$finder
->directories()
->in(array(
dirname(__FILE__) . '/../../../../tmp/cache_minify'
, dirname(__FILE__) . '/../../../../tmp/cache_twig'
__DIR__ . '/../../../../tmp/cache_minify'
, __DIR__ . '/../../../../tmp/cache_twig'
))
->exclude('.git')
->exclude('.svn')
;
->exclude('.svn');
foreach ($finder as $file)
{
$dirs[$file->getPathname()] = $file->getPathname();
@@ -83,17 +83,13 @@ class module_console_systemClearCache extends Command
if(setup::is_installed())
{
$registry = registry::get_instance();
$cache = cache_adapter::get_instance($registry);
if($cache->ping())
{
$cache->flush();
}
$Core = \bootstrap::getCore();
$Core['CacheService']->flushAll();
}
$output->write('Finished !', true);
return;
return 0;
}
}

View File

@@ -42,15 +42,17 @@ class module_console_systemConfigCheck extends Command
$output->writeln('<error>YOU MUST ENABLE GETTEXT SUPPORT TO USE PHRASEANET</error>');
$output->writeln('Canceled');
return;
return 1;
}
$ok = true;
if (setup::is_installed())
{
$registry = registry::get_instance();
$output->writeln(_('*** CHECK BINARY CONFIGURATION ***'));
$this->processConstraints(setup::check_binaries($registry), $output);
$ok = $this->processConstraints(setup::check_binaries($registry), $output) && $ok;
$output->writeln("");
}
else
@@ -58,51 +60,67 @@ class module_console_systemConfigCheck extends Command
$registry = new Setup_Registry();
}
$output->writeln(_('*** FILESYSTEM CONFIGURATION ***'));
$this->processConstraints(setup::check_writability($registry), $output);
$ok = $this->processConstraints(setup::check_writability($registry), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK CACHE OPCODE ***'));
$this->processConstraints(setup::check_cache_opcode(), $output);
$ok = $this->processConstraints(setup::check_cache_opcode(), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK CACHE SERVER ***'));
$this->processConstraints(setup::check_cache_server(), $output);
$ok = $this->processConstraints(setup::check_cache_server(), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK PHP CONFIGURATION ***'));
$this->processConstraints(setup::check_php_configuration(), $output);
$ok = $this->processConstraints(setup::check_php_configuration(), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK PHP EXTENSIONS ***'));
$this->processConstraints(setup::check_php_extension(), $output);
$ok = $this->processConstraints(setup::check_php_extension(), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK PHRASEA ***'));
$this->processConstraints(setup::check_phrasea(), $output);
$ok = $this->processConstraints(setup::check_phrasea(), $output) && $ok;
$output->writeln("");
$output->writeln(_('*** CHECK SYSTEM LOCALES ***'));
$this->processConstraints(setup::check_system_locales(), $output);
$ok = $this->processConstraints(setup::check_system_locales(), $output) && $ok;
$output->writeln("");
$output->write('Finished !', true);
return;
return (int)!$ok;
}
protected function processConstraints(Setup_ConstraintsIterator $constraints, OutputInterface &$output)
{
$hasError = false;
foreach ($constraints as $constraint)
{
$this->processConstraint($constraint, $output);
if (!$hasError && !$this->processConstraint($constraint, $output))
{
$hasError = true;
}
}
return !$hasError;
}
protected function processConstraint(Setup_Constraint $constraint, OutputInterface &$output)
{
$ok = true;
if ($constraint->is_ok())
{
$output->writeln("\t\t<info>" . $constraint->get_message() . '</info>');
}
elseif ($constraint->is_blocker())
{
$output->writeln("\t!!!\t<error>" . $constraint->get_message() . '</error>');
$ok = false;
}
else
{
$output->writeln("\t/!\\\t<comment>" . $constraint->get_message() . '</comment>');
}
return;
return $ok;
}
}

View File

@@ -0,0 +1,311 @@
<?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 KonsoleKomander
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
class module_console_systemExport extends Command
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setDescription('Export all phraseanet records to a directory');
/**
* To implement
*/
// $this->addOption('useoriginalname', 'o', InputOption::VALUE_OPTIONAL
// , 'Use original name for dest files', false);
/**
* To implement
*/
// $this->addOption('excludefield', 'f', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
// , 'Exclude field from XML', array());
/**
* To implement
*/
// $this->addOption('excludestatus', '', InputOption::VALUE_OPTIONAL
// , 'Exclude Status', false);
$this->addOption('docperdir', 'd', InputOption::VALUE_OPTIONAL
, 'Maximum number of files per dir', 100);
$this->addOption('caption', 'c', InputOption::VALUE_OPTIONAL
, 'Export Caption (XML)', false);
$this->addOption('limit', 'l', InputOption::VALUE_OPTIONAL
, 'Limit files quantity (for test purposes)', false);
$this->addOption('base_id', 'b', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
, 'Restrict on base_ids', array());
$this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
, 'Restrict on sbas_ids', array());
$this->addArgument('directory', InputOption::VALUE_REQUIRED
, 'The directory where to export');
$this->addOption('sanitize', '', InputOption::VALUE_REQUIRED
, 'Sanitize filenames. Set to 0 to disable', true);
return $this;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$docPerDir = max(1, (int) $input->getOption('docperdir'));
/**
*
* To implement
*
$useOriginalName = !!$input->getOption('useoriginalname');
$excludeFields = $input->getOption('excludefield');
$exportStatus = !$input->getOption('excludestatus');
*
*/
$Caption = $input->getOption('caption');
$limit = ctype_digit($input->getOption('limit')) ? max(0, (int) $input->getOption('limit')) : false;
$restrictBaseIds = $input->getOption('base_id');
$restrictSbasIds = $input->getOption('sbas_id');
$sanitize = $input->getOption('sanitize');
$export_directory = $input->getArgument('directory');
if (!$export_directory)
{
throw new Exception('Missing directory argument');
}
$export_directory = realpath(substr($export_directory, 0, 1) === '/' ? $export_directory : getcwd() . '/' . $export_directory . '/');
if (!$export_directory)
{
throw new Exception('Export directory does not exists or is not accessible');
}
if (!is_writable($export_directory))
{
throw new Exception('Export directory is not writable');
}
/**
* Sanitize
*/
foreach ($restrictBaseIds as $key => $base_id)
{
$restrictBaseIds[$key] = (int) $base_id;
}
foreach ($restrictSbasIds as $key => $sbas_id)
{
$restrictSbasIds[$key] = (int) $sbas_id;
}
if (count($restrictSbasIds) > 0)
{
$output->writeln("Export datas from selected sbas_ids");
}
elseif (count($restrictBaseIds) > 0)
{
$output->writeln("Export datas from selected base_ids");
}
$appbox = \appbox::get_instance();
$total = $errors = 0;
$unicode = new \unicode();
foreach ($appbox->get_databoxes() as $databox)
{
$output->writeln(sprintf("Processing <info>%s</info>", $databox->get_viewname()));
if (count($restrictSbasIds) > 0 && !in_array($databox->get_sbas_id(), $restrictSbasIds))
{
$output->writeln(sprintf("Databox not selected, bypassing ..."));
continue;
}
$go = true;
$coll_ids = array();
if (count($restrictBaseIds) > 0)
{
$go = false;
foreach ($databox->get_collections() as $collection)
{
if (in_array($collection->get_base_id(), $restrictBaseIds))
{
$go = true;
$coll_ids[] = $collection->get_coll_id();
}
}
}
if (!$go)
{
$output->writeln(sprintf("Collections not selected, bypassing ..."));
continue;
}
$local_export = $export_directory
. '/' . $unicode->remove_nonazAZ09($databox->get_viewname(), true, true)
. '/';
system_file::mkdir($local_export);
$sql = 'SELECT record_id FROM record WHERE parent_record_id = 0 ';
if (count($coll_ids) > 0)
{
$sql .= ' AND coll_id IN (' . implode(', ', $coll_ids) . ') ';
}
$sql .= ' ORDER BY record_id ASC ';
if ($limit)
{
$sql .= ' LIMIT 0, ' . $limit;
}
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$done = 0;
$current_total = count($rs);
$total += $current_total;
$l = strlen((string) $current_total) + 1;
$dir_format = 'datas%' . strlen((string) ceil($current_total / $docPerDir)) . 'd';
$dir_increment = 0;
foreach ($rs as $row)
{
$record = $databox->get_record($row['record_id']);
if (($done % $docPerDir) === 0)
{
$dir_increment++;
$in_dir_files = array();
$current_dir = $local_export . sprintf($dir_format, $dir_increment) . '/';
system_file::mkdir($current_dir);
}
if ($sanitize)
{
$filename = $unicode->remove_nonazAZ09($record->get_original_name(), true, true, true);
}
else
{
$filename = $record->get_original_name();
}
$this->generateDefinitiveFilename($in_dir_files, $filename);
$output_file = $current_dir . $filename;
if (!$this->processRecords($record, $output_file, $Caption))
{
$errors++;
}
$done++;
$output->write(sprintf("\r#%" . $l . "d record remaining", $current_total - $done));
}
$output->writeln(" | " . $current_total . " records done\n");
}
$output->writeln("$total records done, $errors errors occured");
return 0;
}
protected function generateDefinitiveFilename(array &$existing, &$filename)
{
$definitive_filename = $filename;
$suffix = 2;
while (array_key_exists($definitive_filename, $existing))
{
$pathinfo = pathinfo($filename);
$definitive_filename = $pathinfo['filename'] . '_' . $suffix .
(isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '');
$suffix++;
}
$existing[$filename] = $filename;
$filename = $definitive_filename;
return;
}
protected function processRecords(\record_adapter $record, $outfile, $caption)
{
try
{
$file = new system_file($record->get_subdef('document')->get_pathfile());
}
catch (\Exception_Media_SubdefNotFound $e)
{
return false;
}
copy($file->getPathname(), $outfile);
$dest_file = new system_file($outfile);
touch(
$dest_file->getPathname()
, $record->get_creation_date()->format('U')
, $record->get_modification_date()->format('U')
);
switch (strtolower($caption))
{
case 'xml':
$pathinfo = pathinfo($dest_file->getPathname());
$xml_file = dirname($outfile) . '/' . $pathinfo['filename'] . '.xml';
file_put_contents($xml_file, $record->get_xml());
break;
default:
break;
}
return true;
}
}

View File

@@ -43,7 +43,7 @@ class module_console_systemMailCheck extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$output->writeln("Processing...");
@@ -65,7 +65,7 @@ class module_console_systemMailCheck extends Command
$output->write('Finished !', true);
return;
return 0;
}
protected function manage_group($email, $users, $output, $appbox)

View File

@@ -36,16 +36,16 @@ class module_console_systemTemplateGenerator extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
require_once dirname(__FILE__) . '/../../../../lib/vendor/Twig/lib/Twig/Autoloader.php';
require_once dirname(__FILE__) . '/../../../../lib/vendor/Twig-extensions/lib/Twig/Extensions/Autoloader.php';
require_once __DIR__ . '/../../../../lib/vendor/Twig/lib/Twig/Autoloader.php';
require_once __DIR__ . '/../../../../lib/vendor/Twig-extensions/lib/Twig/Extensions/Autoloader.php';
Twig_Autoloader::register();
Twig_Extensions_Autoloader::register();
$tplDir = dirname(__FILE__) . '/../../../../templates/';
$tmpDir = dirname(__FILE__) . '/../../../../tmp/cache_twig/';
$tplDir = __DIR__ . '/../../../../templates/';
$tmpDir = __DIR__ . '/../../../../tmp/cache_twig/';
$loader = new Twig_Loader_Filesystem($tplDir);
$twig = new Twig_Environment($loader, array(
@@ -54,7 +54,9 @@ class module_console_systemTemplateGenerator extends Command
));
$twig->addExtension(new Twig_Extensions_Extension_I18n());
/**
* @todo clean all duplicate filters
*/
$twig->addFilter('serialize', new Twig_Filter_Function('serialize'));
$twig->addFilter('sbas_names', new Twig_Filter_Function('phrasea::sbas_names'));
$twig->addFilter('sbas_name', new Twig_Filter_Function('phrasea::sbas_names'));
@@ -78,9 +80,11 @@ class module_console_systemTemplateGenerator extends Command
$twig->addFilter('key_exists', new Twig_Filter_Function('array_key_exists'));
$twig->addFilter('array_keys', new Twig_Filter_Function('array_keys'));
$twig->addFilter('round', new Twig_Filter_Function('round'));
$twig->addFilter('get_class', new Twig_Filter_Function('get_class'));
$twig->addFilter('formatdate', new Twig_Filter_Function('phraseadate::getDate'));
$twig->addFilter('getPrettyDate', new Twig_Filter_Function('phraseadate::getPrettyString'));
$twig->addFilter('prettyDate', new Twig_Filter_Function('phraseadate::getPrettyString'));
$twig->addFilter('prettyString', new Twig_Filter_Function('phraseadate::getPrettyString'));
$twig->addFilter('formatoctet', new Twig_Filter_Function('p4string::format_octet'));
$twig->addFilter('getDate', new Twig_Filter_Function('phraseadate::getDate'));
$twig->addFilter('geoname_name_from_id', new Twig_Filter_Function('geonames::name_from_id'));
@@ -118,7 +122,7 @@ class module_console_systemTemplateGenerator extends Command
$output->writeln("");
return;
return $n_error;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* This file is part of Phraseanet
*
@@ -36,47 +37,41 @@ class module_console_systemUpgrade extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$Core = \bootstrap::getCore();
if (!setup::is_installed())
{
if (file_exists(dirname(__FILE__) . "/../../../../config/connexion.inc")
&& !file_exists(dirname(__FILE__) . "/../../../../config/config.inc")
&& file_exists(dirname(__FILE__) . "/../../../../config/_GV.php"))
$output->writeln('This version of Phraseanet requires a config/config.yml, config/connexion.yml, config/service.yml');
$output->writeln('Would you like it to be created based on your settings ?');
$dialog = $this->getHelperSet()->get('dialog');
do
{
$output->writeln('This version of Phraseanet requires a config/config.inc');
$output->writeln('Would you like it to be created based on your settings ?');
$dialog = $this->getHelperSet()->get('dialog');
do
{
$continue = mb_strtolower($dialog->ask($output, '<question>' . _('Create automatically') . ' (Y/n)</question>', 'y'));
}
while (!in_array($continue, array('y', 'n')));
if ($continue == 'y')
{
require __DIR__ . "/../../../../config/_GV.php";
$datas = '<?php'."\n"
.'$servername = "'.GV_ServerName.'";'."\n"
.'$maintenance=false;'."\n"
.'$debug=false;'."\n"
.'$debug=true;'."\n"
.'';
file_put_contents(__DIR__ . "/../../../../config/config.inc", $datas);
}
else
{
throw new RuntimeException('Phraseanet is not set up');
}
$continue = mb_strtolower($dialog->ask($output, '<question>' . _('Create automatically') . ' (Y/n)</question>', 'y'));
}
while (!in_array($continue, array('y', 'n')));
if ($continue == 'y')
{
try
{
$connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
$configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
$Core->getConfiguration()->upgradeFromOldConf($configInc, $connexionInc);
}
catch (\Exception $e)
{
}
}
else
{
throw new RuntimeException('Phraseanet is not set up');
}
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$output->write('Phraseanet is going to be upgraded', true);
$dialog = $this->getHelperSet()->get('dialog');
@@ -92,8 +87,9 @@ class module_console_systemUpgrade extends Command
{
try
{
$Core = \bootstrap::getCore();
$output->write('<info>Upgrading...</info>', true);
$appbox = appbox::get_instance();
$appbox = appbox::get_instance($Core);
if (count(User_Adapter::get_wrong_email_users($appbox)) > 0)
{
@@ -101,10 +97,11 @@ class module_console_systemUpgrade extends Command
}
$upgrader = new Setup_Upgrade($appbox);
$advices = $appbox->forceUpgrade($upgrader);
$advices = $appbox->forceUpgrade($upgrader);
}
catch (Exception $e)
catch (\Exception $e)
{
$output->writeln(sprintf('<error>An error occured while upgrading : %s </error>', $e->getMessage()));
}
}

View File

@@ -37,34 +37,45 @@ class module_console_tasklist extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
if(!setup::is_installed())
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Phraseanet is not set up');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$appbox = appbox::get_instance();
$task_manager = new task_manager($appbox);
$tasks = $task_manager->get_tasks();
if(count($tasks) === 0)
$output->writeln ('No tasks on your install !');
foreach($tasks as $task)
try
{
$this->print_task($task, $output);
}
$appbox = appbox::get_instance(\bootstrap::getCore());
$task_manager = new task_manager($appbox);
$tasks = $task_manager->get_tasks();
return $this;
if (count($tasks) === 0)
{
$output->writeln('No tasks on your install !');
}
foreach ($tasks as $task)
{
$this->print_task($task, $output);
}
return 0;
}
catch (\Exception $e)
{
return 1;
}
}
protected function print_task(task_abstract $task, OutputInterface &$output)
{
$message = $task->get_task_id()."\t".($task->get_status() )."\t".$task->get_title();
$message = $task->get_task_id() . "\t" . ($task->get_status() ) . "\t" . $task->get_title();
$output->writeln($message);
return $this;
}
}

View File

@@ -67,12 +67,14 @@ class module_console_taskrun extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
if(!setup::is_installed())
if (!setup::is_installed())
{
throw new RuntimeException('Phraseanet is not set up');
$output->writeln('Phraseanet is not set up');
return 1;
}
require_once dirname(__FILE__) . '/../../../../lib/bootstrap.php';
require_once __DIR__ . '/../../../../lib/bootstrap.php';
$task_id = (int) $input->getArgument('task_id');
@@ -104,8 +106,10 @@ class module_console_taskrun extends Command
$this->task->log(sprintf("%s [%d] taskrun : returned from 'run()', get_status()=%s \n", __FILE__, __LINE__, $this->task->get_status()));
return $this;
}
if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL)
{
$runner = task_abstract::RUNNER_MANUAL;
}
public function tick_handler()
{
@@ -131,4 +135,4 @@ $this->task->log(sprintf("%s [%d] taskrun : returned from 'run()', get_status()=
}
}

View File

@@ -1,172 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod
{
public function get_random()
{
return md5(time() . mt_rand(100000, 999999));
}
public function get_search_datas()
{
$search_datas = array(
'bases' => array(),
'dates' => array(),
'fields' => array()
);
$bases = $fields = $dates = array();
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$searchSet = $user->getPrefs('search');
foreach ($user->ACL()->get_granted_sbas() as $databox)
{
$sbas_id = $databox->get_sbas_id();
$bases[$sbas_id] = array(
'thesaurus' => (trim($databox->get_thesaurus()) != ""),
'cterms' => false,
'collections' => array(),
'sbas_id' => $sbas_id
);
foreach ($user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll)
{
$selected = ($searchSet &&
isset($searchSet->bases) &&
isset($searchSet->bases->$sbas_id)) ? (in_array($coll->get_base_id(), $searchSet->bases->$sbas_id)) : true;
$bases[$sbas_id]['collections'][] =
array(
'selected' => $selected,
'base_id' => $coll->get_base_id()
);
}
$meta_struct = $databox->get_meta_structure();
foreach ($meta_struct as $meta)
{
if (!$meta->is_indexable())
continue;
$id = $meta->get_id();
$name = $meta->get_name();
if ($meta->get_type() == 'date')
{
if (isset($dates[$name]))
$dates[$name]['sbas'][] = $sbas_id;
else
$dates[$name] = array('sbas' => array($sbas_id), 'fieldname' => $name);
}
if (isset($fields[$name]))
{
$fields[$name]['sbas'][] = $sbas_id;
}
else
{
$fields[$name] = array(
'sbas' => array($sbas_id)
, 'fieldname' => $name
, 'type' => $meta->get_type()
, 'id' => $id
);
}
}
if (!$bases[$sbas_id]['thesaurus'])
continue;
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modif_th'))
continue;
if (simplexml_load_string($databox->get_cterms()))
{
$bases[$sbas_id]['cterms'] = true;
}
}
$search_datas['fields'] = $fields;
$search_datas['dates'] = $dates;
$search_datas['bases'] = $bases;
return $search_datas;
}
function getLanguage($lng = false)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$lng = $lng ? $lng : Session_Handler::get_locale();
$registry = $appbox->get_registry();
$out = array();
$out['thesaurusBasesChanged'] = _('prod::recherche: Attention : la liste des bases selectionnees pour la recherche a ete changee.');
$out['confirmDel'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?');
$out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
$out['serverName'] = $registry->get('GV_ServerName');
$out['serverTimeout'] = _('phraseanet::erreur: La connection au serveur Phraseanet semble etre indisponible');
$out['serverDisconnected'] = _('phraseanet::erreur: Votre session est fermee, veuillez vous re-authentifier');
$out['hideMessage'] = _('phraseanet::Ne plus afficher ce message');
$out['confirmGroup'] = _('Supprimer egalement les documents rattaches a ces regroupements');
$out['confirmDelete'] = _('reponses:: Ces enregistrements vont etre definitivement supprimes et ne pourront etre recuperes. Etes vous sur ?');
$out['cancel'] = _('boutton::annuler');
$out['deleteTitle'] = _('boutton::supprimer');
$out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\'');
$out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?');
$out['loading'] = _('phraseanet::chargement');
$out['valider'] = _('boutton::valider');
$out['annuler'] = _('boutton::annuler');
$out['rechercher'] = _('boutton::rechercher');
$out['renewRss'] = _('boutton::renouveller');
$out['candeletesome'] = _('Vous n\'avez pas les droits pour supprimer certains documents');
$out['candeletedocuments'] = _('Vous n\'avez pas les droits pour supprimer ces documents');
$out['needTitle'] = _('Vous devez donner un titre');
$out['newPreset'] = _('Nouveau modele');
$out['fermer'] = _('boutton::fermer');
$out['feed_require_fields'] = _('Vous n\'avez pas rempli tous les champ requis');
$out['feed_require_feed'] = _('Vous n\'avez pas selectionne de fil de publication');
$out['removeTitle'] = _('panier::Supression d\'un element d\'un reportage');
$out['confirmRemoveReg'] = _('panier::Attention, vous etes sur le point de supprimer un element du reportage. Merci de confirmer votre action.');
$out['advsearch_title'] = _('phraseanet::recherche avancee');
$out['bask_rename'] = _('panier:: renommer le panier');
$out['reg_wrong_sbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre');
$out['error'] = _('phraseanet:: Erreur');
$out['warningDenyCgus'] = _('cgus :: Attention, si vous refuser les CGUs de cette base, vous n\'y aures plus acces');
$out['cgusRelog'] = _('cgus :: Vous devez vous reauthentifier pour que vos parametres soient pris en compte.');
$out['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes');
$out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes');
$out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant');
$out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant');
$out['cantDeletePublicOne'] = _('panier:: vous ne pouvez pas supprimer un panier public');
$out['wrongsbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre');
$out['max_record_selected'] = _('Vous ne pouvez pas selectionner plus de 400 enregistrements');
$out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez');
$out['error_test_publi'] = _('Erreur : soit les parametres sont incorrects, soit le serveur distant ne repond pas');
$out['test_publi_ok'] = _('Les parametres sont corrects, le serveur distant est operationnel');
$out['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, verifiez vos parametres');
$out['error_not_published'] = _('Aucune publication effectuee, verifiez vos parametres');
$out['warning_delete_publi'] = _('Attention, en supprimant ce preregalge, vous ne pourrez plus modifier ou supprimer de publications prealablement effectues avec celui-ci');
$out['some_required_fields'] = _('edit::certains documents possedent des champs requis non remplis. Merci de les remplir pour valider votre editing');
$out['nodocselected'] = _('Aucun document selectionne');
return p4string::jsonencode($out);
}
}

View File

@@ -1,324 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod_route_records_abstract
{
/**
*
* @var set_selection
*/
protected $selection;
/**
*
* @var boolean
*/
protected $is_possible;
/**
*
* @var Array
*/
protected $elements_received;
/**
*
* @var Array
*/
protected $single_grouping;
/**
*
* @var int
*/
protected $sbas_id;
/**
*
* @var boolean
*/
protected $has_many_sbas;
/**
*
* @var Array
*/
protected $required_rights = array();
/**
*
* @var Array
*/
protected $required_sbas_rights = array();
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = false;
/**
*
* @var <type>
*/
protected $request;
protected $flatten_groupings = false;
/**
*
* @var boolean
*/
protected $is_basket = false;
/**
*
* @var basket_adapter
*/
protected $original_basket;
/**
*
* @return action_move
*/
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
// $parm = $this->request->get_parms("lst", "ssel");
$this->request = $request;
$this->selection = new set_selection();
$appbox = appbox::get_instance();
$usr_id = $appbox->get_session()->get_usr_id();
if (trim($request->get('ssel')) !== '')
{
$basket = basket_adapter::getInstance($appbox, $request->get('ssel'), $usr_id);
if ($basket->is_grouping() && $this->flatten_groupings === true)
{
foreach ($basket->get_elements() as $basket_element)
{
/* @var $basket_element basket_element_adapter */
$this->selection->add_element($basket_element->get_record());
}
}
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
{
$this->selection->load_list(explode(";", $request->get('lst')), $this->flatten_groupings);
}
$this->elements_received = $this->selection->get_count();
$this->single_grouping = ($this->get_count_actionable() == 1 &&
$this->get_count_actionable_groupings() == 1);
$this->examinate_selection();
return $this;
}
/**
* Tells if the original selection was a basket
*
* @return boolean
*/
public function is_basket()
{
return $this->is_basket;
}
/**
* If the original selection was a basket, returns the basket object
*
* @return basket_adapter
*/
public function get_original_basket()
{
return $this->original_basket;
}
protected function examinate_selection()
{
$this->selection->grep_authorized($this->required_rights, $this->required_sbas_rights);
if ($this->works_on_unique_sbas === true)
{
$this->sbas_ids = $this->selection->get_distinct_sbas_ids();
$this->is_possible = count($this->sbas_ids) == 1;
$this->has_many_sbas = count($this->sbas_ids) > 1;
$this->sbas_id = $this->is_possible ? array_pop($this->sbas_ids) : false;
}
return $this;
}
/**
* Is action applies on single grouping
*
* @return <type>
*/
public function is_single_grouping()
{
return $this->single_grouping;
}
/**
* When action on a single grouping, returns the image of himself
*
* @return record_adapter
*/
public function get_grouping_head()
{
if (!$this->is_single_grouping())
throw new Exception('Cannot use ' . __METHOD__ . ' here');
foreach ($this->get_elements() as $record)
return $record;
}
/**
* Get elements for the action
*
* @return Array
*/
public function get_elements()
{
return $this->selection->get_elements();
}
/**
* Returns true if elements comes from many sbas
*
* @return boolean
*/
public function has_many_sbas()
{
return $this->has_many_sbas;
}
/**
* Returns true if the action is possible with the current elements
* for the user
*
* @return boolean
*/
public function is_possible()
{
return $this->is_possible;
}
/**
* Returns the number of elements on which the action can not be done
*
* @return int
*/
public function get_count_not_actionable()
{
return $this->get_count_element_received() - $this->get_count_actionable();
}
/**
* Returns the number of elements on which the action can be done
*
* @return int
*/
public function get_count_actionable()
{
return $this->selection->get_count();
}
/**
* Returns the number of groupings on which the action can be done
*
* @return int
*/
public function get_count_actionable_groupings()
{
return $this->selection->get_count_groupings();
}
/**
* Return the number of elements receveid when starting action
*
* @return int
*/
public function get_count_element_received()
{
return $this->elements_received;
}
/**
* Return sbas_ids of the current selection
*
* @return int
*/
public function get_sbas_id()
{
return $this->sbas_id;
}
/**
* Get the selection as a serialized string base_id"_"record_id
*
* @return string
*/
public function get_serialize_list()
{
if ($this->is_single_grouping())
return $this->get_grouping_head()->get_serialize_key();
else
return $this->selection->serialize_list();
}
public function get_request()
{
return $this->request;
}
public function set_request($request)
{
$this->request = $request;
}
public function grep_records(Closure $closure)
{
foreach ($this->selection->get_elements() as $record)
{
if (!$closure($record))
$this->selection->remove_element($record);
}
return $this;
}
}

View File

@@ -1,21 +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.
*/
/**
*
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod_route_records_bridge extends module_prod_route_records_abstract
{
}

View File

@@ -1,605 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod_route_records_edit extends module_prod_route_records_abstract
{
/**
*
* @var Array
*/
protected $javascript_fields;
/**
*
* @var Array
*/
protected $fields;
/**
*
* @var Array
*/
protected $javascript_status;
/**
*
* @var Array
*/
protected $javascript_sugg_values;
/**
*
* @var Array
*/
protected $javascript_elements = array();
/**
*
* @var Array
*/
protected $required_rights = array('canmodifrecord');
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = true;
protected $has_thesaurus = false;
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
parent::__construct($request);
if ($this->is_single_grouping())
{
$record = array_pop($this->selection->get_elements());
$children = $record->get_children();
foreach ($children as $child)
{
$this->selection->add_element($child);
}
$n = count($children);
$this->elements_received = $this->selection->get_count() + $n - 1;
$this->examinate_selection();
}
if ($this->is_possible())
{
$this->generate_javascript_fields()
->generate_javascript_sugg_values()
->generate_javascript_status()
->generate_javascript_elements();
}
return $this;
}
public function propose_editing()
{
return $this;
}
public function has_thesaurus()
{
return $this->has_thesaurus;
}
/**
* Return JSON data for UI
*
* @return String
*/
public function get_javascript_elements_ids()
{
return p4string::jsonencode(array_keys($this->javascript_elements));
}
/**
* Return JSON data for UI
*
* @return String
*/
public function get_javascript_elements()
{
return p4string::jsonencode($this->javascript_elements);
}
/**
* Return JSON data for UI
*
* @return String
*/
public function get_javascript_sugg_values()
{
return p4string::jsonencode($this->javascript_sugg_values);
}
/**
* Return JSON data for UI
*
* @return String
*/
public function get_javascript_status()
{
return p4string::jsonencode($this->javascript_status);
}
/**
* Return JSON data for UI
*
* @return String
*/
public function get_javascript_fields()
{
return p4string::jsonencode(($this->javascript_fields));
}
/**
* Return statusbit informations on database
*
* @return Array
*/
public function get_status()
{
return $this->javascript_status;
}
/**
* Return fields informations on database
*
* @return Array
*/
public function get_fields()
{
return $this->fields;
}
/**
* Generate data for JSON UI
*
* @return action_edit
*/
protected function generate_javascript_elements()
{
$_lst = array();
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$twig = new supertwig();
foreach ($this->selection as $record)
{
$indice = $record->get_number();
$_lst[$indice] = array(
'bid' => $record->get_base_id(),
'rid' => $record->get_record_id(),
'sselcont_id' => null,
'_selected' => false
);
$_lst[$indice]['statbits'] = array();
if ($user->ACL()->has_right_on_base($record->get_base_id(), 'chgstatus'))
{
foreach ($this->javascript_status as $n => $s)
{
$tmp_val = substr(strrev($record->get_status()), $n, 1);
$_lst[$indice]['statbits'][$n]['value'] = ($tmp_val == '1') ? '1' : '0';
$_lst[$indice]['statbits'][$n]['dirty'] = false;
}
}
$_lst[$indice]['fields'] = array();
$_lst[$indice]['originalname'] = '';
$_lst[$indice]['originalname'] = $record->get_original_name();
foreach ($record->get_caption()->get_fields() as $field)
{
$meta_struct_id = $field->get_meta_struct_id();
if (!isset($this->javascript_fields[$meta_struct_id]))
{
continue;
}
$_lst[$indice]['fields'][$meta_struct_id] = array(
'dirty' => false,
'meta_id' => $field->get_meta_id(),
'meta_struct_id' => $meta_struct_id,
'value' => $field->get_value()
);
}
$_lst[$indice]['subdefs'] = array('thumbnail' => null, 'preview' => null);
$thumbnail = $record->get_thumbnail();
$_lst[$indice]['subdefs']['thumbnail'] = array(
'url' => $thumbnail->get_url()
, 'w' => $thumbnail->get_width()
, 'h' => $thumbnail->get_height()
);
$_lst[$indice]['preview'] = $twig->render('common/preview.html', array('record' => $record));
try
{
$_lst[$indice]['subdefs']['preview'] = $record->get_subdef('preview');
}
catch (Exception $e)
{
}
$_lst[$indice]['type'] = $record->get_type();
}
$this->javascript_elements = $_lst;
return $this;
}
/**
* Generate data for JSON UI
*
* @return action_edit
*/
protected function generate_javascript_sugg_values()
{
$done = array();
$T_sgval = array();
foreach ($this->selection as $record)
{
/* @var $record record_adapter */
$base_id = $record->get_base_id();
$record_id = $record->get_record_id();
$databox = $record->get_databox();
if (isset($done[$base_id]))
continue;
$T_sgval['b' . $base_id] = array();
$collection = collection::get_from_base_id($base_id);
if ($sxe = simplexml_load_string($collection->get_prefs()))
{
$z = $sxe->xpath('/baseprefs/sugestedValues');
if (!$z || !is_array($z))
continue;
foreach ($z[0] as $ki => $vi) // les champs
{
$field = $databox->get_meta_structure()->get_element_by_name($ki);
if (!$field)
continue; // champ inconnu dans la structure ?
if (!$vi)
continue;
$T_sgval['b' . $base_id][$field->get_id()] = array();
foreach ($vi->value as $oneValue) // les valeurs sug
{
$T_sgval['b' . $base_id][$field->get_id()][] =
(string) $oneValue;
}
}
}
unset($collection);
$done[$base_id] = true;
}
$this->javascript_sugg_values = $T_sgval;
return $this;
}
/**
* Generate data for JSON UI
*
* @return action_edit
*/
protected function generate_javascript_status()
{
$_tstatbits = array();
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
if ($user->ACL()->has_right('changestatus'))
{
$status = databox_status::getDisplayStatus();
if (isset($status[$this->get_sbas_id()]))
{
foreach ($status[$this->get_sbas_id()] as $n => $statbit)
{
$_tstatbits[$n] = array();
$_tstatbits[$n]['label0'] = $statbit['labeloff'];
$_tstatbits[$n]['label1'] = $statbit['labelon'];
$_tstatbits[$n]['img_off'] = $statbit['img_off'];
$_tstatbits[$n]['img_on'] = $statbit['img_on'];
$_tstatbits[$n]['_value'] = 0;
}
}
}
$this->javascript_status = $_tstatbits;
return $this;
}
/**
* Generate data for JSON UI
*
* @return action_edit
*/
protected function generate_javascript_fields()
{
$_tfields = $fields = array();
$this->has_thesaurus = false;
$databox = databox::get_instance($this->get_sbas_id());
$meta_struct = $databox->get_meta_structure();
foreach ($meta_struct as $meta)
{
$fields[] = $meta;
$this->generate_field($meta);
}
$this->fields = $fields;
return $this;
}
protected function generate_field(databox_field $meta)
{
$i = count($this->javascript_fields);
switch ($meta->get_type())
{
case 'datetime':
$format = _('phraseanet::technique::datetime-edit-format');
$explain = _('phraseanet::technique::datetime-edit-explain');
break;
case 'date':
$format = _('phraseanet::technique::date-edit-format');
$explain = _('phraseanet::technique::date-edit-explain');
break;
case 'time':
$format = _('phraseanet::technique::time-edit-format');
$explain = _('phraseanet::technique::time-edit-explain');
break;
default:
$format = $explain = "";
break;
}
$regfield = ($meta->is_regname() || $meta->is_regdesc() || $meta->is_regdate());
$separator = $meta->get_separator();
$datas = array(
'meta_struct_id' => $meta->get_id()
, 'name' => $meta->get_name()
, '_status' => 0
, '_value' => ''
, '_sgval' => array()
, 'required' => $meta->is_required()
, 'readonly' => $meta->is_readonly()
, 'type' => $meta->get_type()
, 'format' => $format
, 'explain' => $explain
, 'tbranch' => $meta->get_tbranch()
, 'maxLength' => $meta->get_source()->maxlength()
, 'minLength' => $meta->get_source()->minLength()
, 'regfield' => $regfield
, 'multi' => $meta->is_multi()
, 'separator' => $separator
);
if (trim($meta->get_tbranch()) !== '')
$this->has_thesaurus = true;
$this->javascript_fields[$meta->get_id()] = $datas;
}
/**
* Substitute Head file of groupings and save new Desc
*
* @param http_request $request
* @return action_edit
*/
public function execute(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
if ($request->get('act_option') == 'SAVEGRP' && $request->get('newrepresent'))
{
try
{
$reg_record = $this->get_grouping_head();
$reg_sbas_id = $reg_record->get_sbas_id();
$newsubdef_reg = new record_adapter($reg_sbas_id, $request->get('newrepresent'));
if ($newsubdef_reg->get_type() !== 'image')
throw new Exception('A reg image must come from image data');
foreach ($newsubdef_reg->get_subdefs() as $name => $value)
{
$pathfile = $value->get_pathfile();
$system_file = new system_file($pathfile);
$reg_record->substitute_subdef($name, $system_file);
}
}
catch (Exception $e)
{
}
}
if (!is_array($request->get('mds')))
return $this;
$sbas_id = (int) $request->get('sbid');
$databox = databox::get_instance($sbas_id);
$meta_struct = $databox->get_meta_structure();
$write_edit_el = false;
$date_obj = new DateTime();
foreach ($meta_struct->get_elements() as $meta_struct_el)
{
if ($meta_struct_el->get_metadata_namespace() == "PHRASEANET" && $meta_struct_el->get_metadata_tagname() == 'tf-editdate')
$write_edit_el = $meta_struct_el;
}
$elements = $this->selection->get_elements();
foreach ($request->get('mds') as $rec)
{
try
{
$record = $databox->get_record($rec['record_id']);
}
catch (Exception $e)
{
continue;
}
$key = $record->get_serialize_key();
if (!array_key_exists($key, $elements))
continue;
$statbits = $rec['status'];
$editDirty = $rec['edit'];
if ($editDirty == '0')
$editDirty = false;
else
$editDirty = true;
if (is_array($rec['metadatas']))
{
$record->set_metadatas($rec['metadatas']);
}
if ($write_edit_el instanceof databox_field)
{
$fields = $record->get_caption()->get_fields(array($write_edit_el->get_name()));
$field = array_pop($fields);
$metas = array(
array(
'meta_struct_id' => $write_edit_el->get_id()
, 'meta_id' => ($field ? $field->get_meta_id() : null)
, 'value' => array($date_obj->format('Y-m-d h:i:s'))
)
);
$record->set_metadatas($metas, true);
}
$newstat = $record->get_status();
$statbits = ltrim($statbits, 'x');
if (!in_array($statbits, array('', 'null')))
{
$mask_and = ltrim(str_replace(
array('x', '0', '1', 'z'), array('1', 'z', '0', '1'), $statbits), '0');
if ($mask_and != '')
$newstat = databox_status::operation_and_not($newstat, $mask_and);
$mask_or = ltrim(str_replace('x', '0', $statbits), '0');
if ($mask_or != '')
$newstat = databox_status::operation_or($newstat, $mask_or);
$record->set_binary_status($newstat);
}
$record->write_metas();
if ($statbits != '')
{
$appbox->get_session()
->get_logger($record->get_databox())
->log($record, Session_Logger::EVENT_STATUS, '', '');
}
if ($editDirty)
{
$appbox->get_session()
->get_logger($record->get_databox())
->log($record, Session_Logger::EVENT_EDIT, '', '');
}
}
return $this;
// foreach ($trecchanges as $fname => $fchange)
// {
// $bool = false;
// if ($regfields && $parm['act_option'] == 'SAVEGRP'
// && $fname == $regfields['regname'])
// {
// try
// {
// $basket = basket_adapter::getInstance($parm['ssel']);
// $basket->name = implode(' ', $fchange['values']);
// $basket->save();
// $bool = true;
// }
// catch (Exception $e)
// {
// echo $e->getMessage();
// }
// }
// if ($regfields && $parm['act_option'] == 'SAVEGRP'
// && $fname == $regfields['regdesc'])
// {
// try
// {
// $basket = basket_adapter::getInstance($parm['ssel']);
// $basket->desc = implode(' ', $fchange['values']);
// $basket->save();
// $bool = true;
// }
// catch (Exception $e)
// {
// echo $e->getMessage();
// }
// }
// if ($bool)
// {
// try
// {
// $basket = basket_adapter::getInstance($parm['ssel']);
// $basket->delete_cache();
// }
// catch (Exception $e)
// {
//
// }
// }
// }
//
// return $this;
}
}

View File

@@ -1,51 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod_route_records_feed extends module_prod_route_records_abstract
{
/**
*
* @var Array
*/
protected $required_sbas_rights = array('cbas_chupub');
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = true;
protected $flatten_groupings = true;
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
parent::__construct($request);
if ($this->is_single_grouping())
{
$record = array_pop($this->selection->get_elements());
foreach ($record->get_children() as $child)
{
$this->selection->add_element($child);
}
}
return $this;
}
}

View File

@@ -1,127 +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
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_prod_route_records_move extends module_prod_route_records_abstract
{
/**
*
* @var Array
*/
protected $required_rights = array('candeleterecord');
/**
*
* @var Array
*/
protected $available_destinations;
/**
*
*/
protected $works_on_unique_sbas = true;
/**
* Constructor
*
* @return action_move
*/
public function __construct(Symfony\Component\HttpFoundation\Request $request)
{
parent::__construct($request);
$this->evaluate_destinations();
return $this;
}
/**
* Check which collections can receive the documents
*
* @return action_move
*/
protected function evaluate_destinations()
{
$this->available_destinations = array();
if (!$this->is_possible)
return $this;
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$this->available_destinations = array_keys($user->ACL()->get_granted_base(array('canaddrecord'), array($this->sbas_id)));
return $this;
}
/**
* Returns an array of base_id
*
* @return Array
*/
public function available_destination()
{
return $this->available_destinations;
}
public function propose()
{
return $this;
}
/**
*
* @param http_request $request
* @return action_move
*/
public function execute(Symfony\Component\HttpFoundation\Request $request)
{
$appbox = appbox::get_instance();
$session = $appbox->get_session();
$user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
$base_dest =
$user->ACL()->has_right_on_base($request->get('base_id'), 'canaddrecord') ?
$request->get('base_id') : false;
if (!$this->is_possible())
throw new Exception('This action is not possible');
if ($request->get("chg_coll_son") == "1")
{
foreach ($this->selection as $record)
{
if (!$record->is_grouping())
continue;
foreach ($record->get_children() as $child)
{
if (!$user->ACL()->has_right_on_base(
$child->get_base_id(), 'candeleterecord'))
continue;
$this->selection->add_element($child);
}
}
}
$collection = collection::get_from_base_id($base_dest);
foreach ($this->selection as $record)
{
$record->move_to_collection($collection, $appbox);
}
return $this;
}
}

View File

@@ -245,7 +245,7 @@ class module_report
*/
public function __construct($d1, $d2, $sbas_id, $collist)
{
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$session = $appbox->get_session();
$this->dmin = $d1;
$this->dmax = $d2;

View File

@@ -341,7 +341,7 @@ class module_report_activity extends module_report
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$login = User_Adapter::getInstance($usr, appbox::get_instance())->get_display_name();
$login = User_Adapter::getInstance($usr, appbox::get_instance(\bootstrap::getCore()))->get_display_name();
$this->setChamp($rs);
($config) ? $this->setConfigColumn($config) :
@@ -453,7 +453,6 @@ class module_report_activity extends module_report
$this->result[$i]['total'] += 1;
$total['tot_dl'] += 1;
}
$nb_row = $i + 1;
@@ -479,7 +478,7 @@ class module_report_activity extends module_report
* @param string $on choose the field on what you want the result
* @return array
*/
public function getConnexionBase($tab = false, $on= "")
public function getConnexionBase($tab = false, $on = "")
{
//default group on user column
if (empty($on))
@@ -577,7 +576,7 @@ class module_report_activity extends module_report
* @param array $tab config for the html table
* @return array
*/
public function getDetailDownload($tab = false, $on="")
public function getDetailDownload($tab = false, $on = "")
{
empty($on) ? $on = "user" : ""; //by default always report on user
@@ -638,19 +637,37 @@ class module_report_activity extends module_report
foreach ($rs as $row)
{
$user = $row[$on];
if (($save_user != $user) && !is_null($user))
if (($save_user != $user) && !is_null($user) && !empty($user))
{
if ($i >= 0)
{
if (($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc']) == 0 || ($this->result[$i]['poiddoc'] + $this->result[$i]['poidprev']) == 0)
{
unset($this->result[$i]);
}
if (isset($this->result[$i]['poiddoc']) && isset($this->result[$i]['poidprev']))
{
$this->result[$i]['poiddoc'] = p4string::format_octets($this->result[$i]['poiddoc']);
$this->result[$i]['poidprev'] = p4string::format_octets($this->result[$i]['poidprev']);
}
}
$i++;
$this->result[$i]['nbprev'] = 0;
$this->result[$i]['poidprev'] = 0;
$this->result[$i]['nbdoc'] = 0;
$this->result[$i]['poiddoc'] = 0;
}
//doc info
if ($row['final'] == 'document' &&
!is_null($user) && !is_null($row['usrid']))
{
$this->result[$i]['nbdoc'] = (!is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['poiddoc'] = (!is_null($row['poid']) ?
p4string::format_octets($row['poid']) : 0);
if (!isset($this->result[$i]['nbprev']))
$this->result[$i]['nbprev'] = 0;
if (!isset($this->result[$i]['poidprev']))
$this->result[$i]['poidprev'] = 0;
$this->result[$i]['poiddoc'] = (!is_null($row['poid']) ? $row['poid'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . _('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbdoc'] += $this->result[$i]['nbdoc'];
@@ -658,26 +675,25 @@ class module_report_activity extends module_report
$this->result[$i]['usrid'] = $row['usrid'];
}
//preview info
if ($row['final'] == 'preview' &&
if (($row['final'] == 'preview' || $row['final'] == 'thumbnail') &&
!is_null($user) &&
!is_null($row['usrid']))
{
if (!isset($this->result[$i]['nbdoc']))
$this->result[$i]['nbdoc'] = 0;
if (!isset($this->result[$i]['poiddoc']))
$this->result[$i]['poiddoc'] = 0;
$this->result[$i]['nbprev'] = (!is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['poidprev'] = (!is_null($row['poid']) ?
p4string::format_octets($row['poid']) : 0);
$this->result[$i]['nbprev'] += (!is_null($row['nb']) ? $row['nb'] : 0);
$this->result[$i]['poidprev'] += (!is_null($row['poid']) ? $row['poid'] : 0);
$this->result[$i]['user'] = empty($row[$on]) ?
"<i>" . _('report:: non-renseigne') . "</i>" : $row[$on];
$total['nbprev'] += $this->result[$i]['nbprev'];
$total['nbprev'] += (!is_null($row['nb']) ? $row['nb'] : 0);
$total['poidprev'] += (!is_null($row['poid']) ? $row['poid'] : 0);
$this->result[$i]['usrid'] = $row['usrid'];
}
$save_user = $user;
}
unset($this->result[$i]);
$nb_row = $i + 1;
$this->total = $nb_row;
@@ -739,7 +755,7 @@ class module_report_activity extends module_report
$this->setChamp($rs);
$this->initDefaultConfigColumn($this->champ);
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$i = 0;
foreach ($rs as $row)

View File

@@ -77,7 +77,7 @@ class module_report_add extends module_report
$ret = array();
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
foreach ($rs as $row)
{

View File

@@ -66,7 +66,7 @@ class module_report_dashboard_feed implements module_report_dashboard_componentI
*/
public static function getInstance($sbasid, $sbas_coll, $dmin, $dmax)
{
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$cache_id = 'feed_' . md5($sbasid . '_' . $sbas_coll . '_' . $dmin . '_' . $dmax);
try

View File

@@ -47,7 +47,7 @@ class module_report_edit extends module_report
public function __construct($arg1, $arg2, $sbas_id, $collist)
{
parent::__construct($arg1, $arg2, $sbas_id, $collist);
$this->title = _('report:: document ajoute');
$this->title = _('report:: edited documents');
}
/**
@@ -76,7 +76,7 @@ class module_report_edit extends module_report
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$appbox = appbox::get_instance();
$appbox = appbox::get_instance(\bootstrap::getCore());
$ret = array();
foreach ($rs as $row)

View File

@@ -47,7 +47,7 @@ class module_report_push extends module_report
public function __construct($arg1, $arg2, $sbas_id, $collist)
{
parent::__construct($arg1, $arg2, $sbas_id, $collist);
$this->title = _('report:: document ajoute');
$this->title = _('report:: pushed documents');
}
/**

View File

@@ -70,7 +70,6 @@ class module_report_sqldownload extends module_report_sql implements module_repo
$this->sql .= $this->filter->getOrderFilter() ? : '';
// var_dump(str_replace(array_keys($this->params), array_values($this->params), $this->sql), $this->sql, $this->params);
$stmt = $this->connbas->prepare($this->sql);
$stmt->execute($this->params);
$this->total_row = $stmt->rowCount();

View File

@@ -47,7 +47,7 @@ class module_report_validate extends module_report
public function __construct($arg1, $arg2, $sbas_id, $collist)
{
parent::__construct($arg1, $arg2, $sbas_id, $collist);
$this->title = _('report:: document ajoute');
$this->title = _('report:: validated documents');
}
/**