Merge with 3.7

This commit is contained in:
Romain Neutron
2012-11-07 16:16:13 +01:00
28 changed files with 540 additions and 576 deletions

View File

@@ -109,6 +109,28 @@ class Bridge implements ControllerProviderInterface
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $account->get_api()->get_connector()->get_default_element_type() . '/'); return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $account->get_api()->get_connector()->get_default_element_type() . '/');
})->assert('account_id', '\d+'); })->assert('account_id', '\d+');
$controllers->post('/adapter/{account_id}/delete/'
, function($account_id) use ($app) {
$success = false;
$message = '';
try {
$account = \Bridge_Account::load_account($app['phraseanet.appbox'], $account_id);
if ($account->get_user()->get_id() !== $app->getAuthenticatedUser()->get_id()) {
throw new HttpException(403, 'Access forbiden');
}
$account->delete();
$success = true;
} catch(\Bridge_Exception_AccountNotFound $e) {
$message = _('Account is not found.');
} catch(\Exception $e) {
$message = _('Something went wrong, please contact an administrator');
}
return $app->json(array('success' => $success, 'message' => $message));
})->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-records/', function(Application $app, $account_id) { $controllers->get('/adapter/{account_id}/load-records/', function(Application $app, $account_id) {
$page = max((int) $app['request']->query->get('page'), 0); $page = max((int) $app['request']->query->get('page'), 0);
$quantity = 10; $quantity = 10;

View File

@@ -88,7 +88,7 @@ class Prod extends Helper
continue; continue;
} }
if (simplexml_load_string($databox->get_cterms())) { if (false !== simplexml_load_string($databox->get_cterms())) {
$bases[$sbas_id]['cterms'] = true; $bases[$sbas_id]['cterms'] = true;
} }
} }

View File

@@ -349,8 +349,9 @@ class PDF
$collection = \collection::get_from_base_id($this->app, $rec->get_base_id()); $collection = \collection::get_from_base_id($this->app, $rec->get_base_id());
$vn = ""; $vn = "";
if ($str = simplexml_load_string($collection->get_prefs())) if (false !== $str = simplexml_load_string($collection->get_prefs())) {
$vn = (string) ($str->pdfPrintappear); $vn = (string) ($str->pdfPrintappear);
}
if ($vn == "" || $vn == "1") { if ($vn == "" || $vn == "1") {
$RIGHT_TEXT = \phrasea::bas_names($rec->get_base_id(), $this->app); $RIGHT_TEXT = \phrasea::bas_names($rec->get_base_id(), $this->app);

View File

@@ -631,7 +631,7 @@ class Bridge_Api_Youtube extends Bridge_Api_Abstract implements Bridge_Api_Inter
$xml = simplexml_load_string($string); $xml = simplexml_load_string($string);
libxml_clear_errors(); libxml_clear_errors();
if ( ! $xml) { if (false === $xml) {
return false; return false;
} }
@@ -723,11 +723,10 @@ class Bridge_Api_Youtube extends Bridge_Api_Abstract implements Bridge_Api_Inter
$cat = array(); $cat = array();
$url_cat = sprintf('%s?hl=%s', self::CATEGORY_URL, $this->get_locale()); $url_cat = sprintf('%s?hl=%s', self::CATEGORY_URL, $this->get_locale());
$cxml = @simplexml_load_file($url_cat); if (false === $cxml = simplexml_load_file($url_cat)) {
if ( ! $cxml)
throw new Bridge_Exception_ApiConnectorRequestFailed('Failed to retrive youtube categories'); throw new Bridge_Exception_ApiConnectorRequestFailed('Failed to retrive youtube categories');
}
$cxml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom'); $cxml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
$categories = $cxml->xpath('//atom:category'); $categories = $cxml->xpath('//atom:category');

View File

@@ -358,10 +358,9 @@ abstract class base implements cache_cacheableInterface
return $this; return $this;
} }
$structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml"); if (false === $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml")) {
if ( ! $structure)
throw new Exception('Unable to load schema'); throw new Exception('Unable to load schema');
}
if ($this->get_base_type() === self::APPLICATION_BOX) if ($this->get_base_type() === self::APPLICATION_BOX)
$this->schema = $structure->appbox; $this->schema = $structure->appbox;

View File

@@ -1009,7 +1009,7 @@ class databox extends base
$thesaurus = $this->get_thesaurus(); $thesaurus = $this->get_thesaurus();
if ($thesaurus && ($tmp = simplexml_load_string($thesaurus)) !== false) if ($thesaurus && false !== $tmp = simplexml_load_string($thesaurus))
self::$_sxml_thesaurus[$sbas_id] = $tmp; self::$_sxml_thesaurus[$sbas_id] = $tmp;
else else
self::$_sxml_thesaurus[$sbas_id] = false; self::$_sxml_thesaurus[$sbas_id] = false;
@@ -1174,7 +1174,7 @@ class databox extends base
$structure = $this->get_structure(); $structure = $this->get_structure();
if ($structure && ($tmp = simplexml_load_string($structure)) !== false) if ($structure && false !== $tmp = simplexml_load_string($structure))
$this->_sxml_structure = $tmp; $this->_sxml_structure = $tmp;
else else
$this->_sxml_structure = false; $this->_sxml_structure = false;

View File

@@ -78,7 +78,7 @@ class databox_status
$xmlpref = $databox->get_structure(); $xmlpref = $databox->get_structure();
$sxe = simplexml_load_string($xmlpref); $sxe = simplexml_load_string($xmlpref);
if ($sxe) { if ($sxe !== false) {
foreach ($sxe->statbits->bit as $sb) { foreach ($sxe->statbits->bit as $sb) {
$bit = (int) ($sb["n"]); $bit = (int) ($sb["n"]);

View File

@@ -112,7 +112,7 @@ function giveMeBases(Application $app, $usr = null)
$collInscript = $baseInscript; $collInscript = $baseInscript;
$defined = false; $defined = false;
$cguSpec = false; $cguSpec = false;
if ($xml = simplexml_load_string($collection->get_prefs())) { if (false !== $xml = simplexml_load_string($collection->get_prefs())) {
$defined = true; $defined = true;
foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript) { foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript) {
$tmp = (string) $caninscript; $tmp = (string) $caninscript;

View File

@@ -33,7 +33,7 @@ class geonames
$sxe = simplexml_load_string($xml); $sxe = simplexml_load_string($xml);
if ($sxe && ($geoname = $sxe->geoname)) { if ($sxe !== false && ($geoname = $sxe->geoname)) {
$ret = (string) $geoname->city . ', ' . (string) $geoname->country; $ret = (string) $geoname->city . ', ' . (string) $geoname->country;
} }
} }
@@ -56,7 +56,7 @@ class geonames
if ($xml) { if ($xml) {
$sxe = simplexml_load_string($xml); $sxe = simplexml_load_string($xml);
if ($sxe && ($geoname = $sxe->geoname)) { if ($sxe !== false && ($geoname = $sxe->geoname)) {
$ret = (string) $geoname->country; $ret = (string) $geoname->country;
} }
} }
@@ -76,7 +76,7 @@ class geonames
if ($xml) { if ($xml) {
$sxe = simplexml_load_string($xml); $sxe = simplexml_load_string($xml);
if ($sxe && ($geoname = $sxe->geoname)) { if ($sxe !== false && ($geoname = $sxe->geoname)) {
$ret = (string) $geoname->country_code; $ret = (string) $geoname->country_code;
} }
} }
@@ -157,7 +157,7 @@ class geonames
$xml = http_query::getUrl($url); $xml = http_query::getUrl($url);
if ($xml) { if ($xml) {
$sxe = simplexml_load_string($xml); $sxe = simplexml_load_string($xml);
if ($sxe && $sxe->geoname) { if ($sxe !== false && $sxe->geoname) {
$output['city'] = (string) $sxe->geoname->city; $output['city'] = (string) $sxe->geoname->city;
$output['country_code'] = (string) $sxe->geoname->country_code; $output['country_code'] = (string) $sxe->geoname->country_code;
$output['country'] = (string) $sxe->geoname->country; $output['country'] = (string) $sxe->geoname->country;

View File

@@ -83,7 +83,7 @@ class patch_370a8 implements patchInterface
* migrating task 'workflow01' or 'task_period_ftv' * migrating task 'workflow01' or 'task_period_ftv'
*/ */
$x = $task['settings']; $x = $task['settings'];
if (($sx = simplexml_load_string($x)) !== FALSE) { if (false !== $sx = simplexml_load_string($x)) {
$period = (int) ($sx->period); $period = (int) ($sx->period);
if ( ! array_key_exists('_' . $period, $tdom)) { if ( ! array_key_exists('_' . $period, $tdom)) {

View File

@@ -35,8 +35,8 @@ class queries
} }
$cssTopics = ''; $cssTopics = '';
if ($xmlTopics && ($sxTopics = simplexml_load_file($xmlTopics))) { if ($xmlTopics && false !== $sxTopics = simplexml_load_file($xmlTopics)) {
$cssTopics = (string) ($sxTopics->display->css); $cssTopics = (string) $sxTopics->display->css;
} }
$out .= '<style type="text/css"> $out .= '<style type="text/css">
@@ -96,7 +96,7 @@ class queries
$jsTopics = 'null'; $jsTopics = 'null';
$maxdepth = 0; $maxdepth = 0;
if (($sxTopics = simplexml_load_file($xmlTopics))) { if (false !== $sxTopics = simplexml_load_file($xmlTopics)) {
$jsTopics = self::topicsAsJS($sxTopics->topics, 0, $maxdepth); $jsTopics = self::topicsAsJS($sxTopics->topics, 0, $maxdepth);
} }

View File

@@ -601,7 +601,7 @@ class searchEngine_adapter_phrasea_engine extends searchEngine_adapter_abstract
$sxe = simplexml_load_string($res['xml']); $sxe = simplexml_load_string($res['xml']);
foreach ($fields as $name => $field) { foreach ($fields as $name => $field) {
if ($sxe && $sxe->description && $sxe->description->$name) { if (false !== $sxe && $sxe->description && $sxe->description->$name) {
$val = array(); $val = array();
foreach ($sxe->description->$name as $value) { foreach ($sxe->description->$name as $value) {
$val[] = str_replace(array('[[em]]', '[[/em]]'), array('<em>', '</em>'), (string) $value); $val[] = str_replace(array('[[em]]', '[[/em]]'), array('<em>', '</em>'), (string) $value);

View File

@@ -35,6 +35,7 @@ class task_Scheduler
public function __construct(Application $application, Logger $logger) public function __construct(Application $application, Logger $logger)
{ {
declare(ticks = 1);
$this->dependencyContainer = $application; $this->dependencyContainer = $application;
$this->logger = $logger; $this->logger = $logger;
} }
@@ -50,6 +51,14 @@ class task_Scheduler
* @throws Exception if scheduler is already running * @throws Exception if scheduler is already running
* @todo doc all possible exception * @todo doc all possible exception
*/ */
public function sigHandler($signal)
{
$status = null;
$pid = pcntl_wait($status);
$exitstatus = pcntl_wexitstatus($status);
$this->log(sprintf("sigchild %s received from pid=%s, status=%s, exitstatus=%s\n", $signal, $pid, var_export($status, true), $exitstatus));
}
public function run() public function run()
{ {
//prevent scheduler to fail if GV_cli is not provided //prevent scheduler to fail if GV_cli is not provided
@@ -67,7 +76,10 @@ class task_Scheduler
if (\task_manager::isPosixPcntlSupported()) { if (\task_manager::isPosixPcntlSupported()) {
// avoid <defunct> php when a task ends // avoid <defunct> php when a task ends
pcntl_signal(SIGCHLD, SIG_IGN); // pcntl_signal(SIGCHLD, SIG_IGN); // no zombies but no returnValue
// pcntl_signal(SIGCHLD, SIG_DFL); // with "declare(ticks=1)" returnValue ok but zombies
pcntl_signal(SIGCHLD, array($this, 'sigHandler')); // ok
$this->method = self::METHOD_FORK; $this->method = self::METHOD_FORK;
} }

View File

@@ -140,8 +140,7 @@ abstract class task_abstract
$this->completed_percentage = (int) $row['completed']; $this->completed_percentage = (int) $row['completed'];
$this->settings = $row['settings']; $this->settings = $row['settings'];
$sx = @simplexml_load_string($this->settings); if (false !== $sx = @simplexml_load_string($this->settings)) {
if ($sx) {
$this->loadSettings($sx); $this->loadSettings($sx);
} }
} }

View File

@@ -96,8 +96,7 @@ class task_period_RecordMover extends task_appboxAbstract
*/ */
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
// ... but we could check for safe values
if ((int) ($sxml->period) < 10) if ((int) ($sxml->period) < 10)
$sxml->period = 10; $sxml->period = 10;
elseif ((int) ($sxml->period) > 1440) // 1 jour elseif ((int) ($sxml->period) > 1440) // 1 jour
@@ -417,8 +416,8 @@ class task_period_RecordMover extends task_appboxAbstract
protected function retrieveContent(appbox $appbox) protected function retrieveContent(appbox $appbox)
{ {
$this->maxrecs = 1000; $this->maxrecs = 1000;
$this->sxTaskSettings = @simplexml_load_string($this->getSettings()); $this->sxTaskSettings = simplexml_load_string($this->getSettings());
if ( ! $this->sxTaskSettings || ! $this->sxTaskSettings->tasks) { if (false === $this->sxTaskSettings || !$this->sxTaskSettings->tasks) {
return array(); return array();
} }

View File

@@ -288,7 +288,7 @@ class task_period_archive extends task_abstract
$this->period = 60; $this->period = 60;
$this->cold = 30; $this->cold = 30;
if (($this->sxBasePrefs = simplexml_load_string($collection->get_prefs())) != false) { if (false !== $this->sxBasePrefs = @simplexml_load_string($collection->get_prefs())) {
$this->sxBasePrefs["id"] = $base_id; $this->sxBasePrefs["id"] = $base_id;
$this->period = (int) ($this->sxTaskSettings->period); $this->period = (int) ($this->sxTaskSettings->period);
@@ -387,7 +387,7 @@ class task_period_archive extends task_abstract
$this->setLastExecTime(); $this->setLastExecTime();
try { try {
if ( ! ($this->sxTaskSettings = @simplexml_load_string($this->getSettings()))) { if (false === $this->sxTaskSettings = simplexml_load_string($this->getSettings())) {
throw new Exception(sprintf('Error fetching or reading settings of the task \'%d\'', $this->getID())); throw new Exception(sprintf('Error fetching or reading settings of the task \'%d\'', $this->getID()));
} else { } else {
// copy settings to task, so it's easier to get later // copy settings to task, so it's easier to get later
@@ -599,10 +599,10 @@ class task_period_archive extends task_abstract
if ($this->movedFiles) { if ($this->movedFiles) {
// something happened : a least one file has moved // something happened : a least one file has moved
return self::STATE_MAXRECSDONE; return 'MAXRECSDONE';
} elseif (memory_get_usage() >> 20 > 25) { } elseif (memory_get_usage() >> 20 > 25) {
return self::STATE_MAXMEGSREACHED; return 'MAXMEGSREACHED';
} else { } else {
return 'NORECSTODO'; return 'NORECSTODO';
@@ -683,7 +683,7 @@ class task_period_archive extends task_abstract
try { try {
$listFolder = new CListFolder($path); $listFolder = new CListFolder($path);
if (($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) != false) { if (false !== $sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) {
// test for magic file // test for magic file
if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') { if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') {
@@ -790,7 +790,7 @@ class task_period_archive extends task_abstract
$xp = new DOMXPath($dom); $xp = new DOMXPath($dom);
if (($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) != false) { if (false !== $sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) {
// test magicfile // test magicfile
if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') { if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') {
@@ -1564,7 +1564,7 @@ class task_period_archive extends task_abstract
// a .grouping.xml must stay in place // a .grouping.xml must stay in place
// -- don't do, done in phase4 // -- don't do, done in phase4
$sxGrouping = simplexml_load_file($groupingFile); $sxGrouping = @simplexml_load_file($groupingFile);
$grp_rid = $sxGrouping['grouping']; $grp_rid = $sxGrouping['grouping'];
$this->archiveFilesToGrp($dom, $node, $path . '/' . $grpFolder $this->archiveFilesToGrp($dom, $node, $path . '/' . $grpFolder
@@ -1615,7 +1615,7 @@ class task_period_archive extends task_abstract
if ($captionFile !== null && true === $this->dependencyContainer['filesystem']->exists($captionFile)) { if ($captionFile !== null && true === $this->dependencyContainer['filesystem']->exists($captionFile)) {
$caption = $this->readXMLForDatabox($metadatasStructure, $captionFile); $caption = $this->readXMLForDatabox($metadatasStructure, $captionFile);
$captionStatus = $this->parseStatusBit(simplexml_load_file($captionFile)); $captionStatus = $this->parseStatusBit(@simplexml_load_file($captionFile));
if ($captionStatus) { if ($captionStatus) {
$status = databox_status::operation_or($this->dependencyContainer, $status, $captionStatus); $status = databox_status::operation_or($this->dependencyContainer, $status, $captionStatus);
@@ -1680,7 +1680,7 @@ class task_period_archive extends task_abstract
if ($captionFile !== null && true === $this->dependencyContainer['filesystem']->exists($captionFile)) { if ($captionFile !== null && true === $this->dependencyContainer['filesystem']->exists($captionFile)) {
$caption = $this->readXMLForDatabox($metadatasStructure, $captionFile); $caption = $this->readXMLForDatabox($metadatasStructure, $captionFile);
$captionStatus = $this->parseStatusBit(simplexml_load_file($captionFile)); $captionStatus = $this->parseStatusBit(@simplexml_load_file($captionFile));
if ($captionStatus) { if ($captionStatus) {
$status = databox_status::operation_or($this->dependencyContainer, $status, $captionStatus); $status = databox_status::operation_or($this->dependencyContainer, $status, $captionStatus);
@@ -2184,9 +2184,7 @@ class task_period_archive extends task_abstract
throw new \InvalidArgumentException(sprintf('file %s does not exists', $pathfile)); throw new \InvalidArgumentException(sprintf('file %s does not exists', $pathfile));
} }
$sxcaption = @simplexml_load_file($pathfile); if (false === $sxcaption = @simplexml_load_file($pathfile)) {
if ( ! $sxcaption) {
throw new \InvalidArgumentException(sprintf('Invalid XML file %s', $pathfile)); throw new \InvalidArgumentException(sprintf('Invalid XML file %s', $pathfile));
} }
@@ -2236,15 +2234,17 @@ class task_period_archive extends task_abstract
* @param \SimpleXMLElement $sxcaption The SimpleXML related to the XML * @param \SimpleXMLElement $sxcaption The SimpleXML related to the XML
* @return string * @return string
*/ */
protected function parseStatusBit(\SimpleXMLElement $sxcaption) protected function parseStatusBit($sxcaption)
{ {
$statBit = null; if (!$sxcaption instanceof SimpleXMLElement) {
return null;
if ('' !== $inStatus = (string) $sxcaption->status) {
$statBit = $inStatus;
} }
return $statBit; if ('' !== $inStatus = (string) $sxcaption->status) {
return $inStatus;
}
return null;
} }
} }

View File

@@ -168,7 +168,7 @@ class task_period_cindexer extends task_abstract
*/ */
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
?> ?>
<script type="text/javascript"> <script type="text/javascript">
<?php echo $form ?>.binpath.value = "<?php echo p4string::MakeString($sxml->binpath, "js", '"') ?>"; <?php echo $form ?>.binpath.value = "<?php echo p4string::MakeString($sxml->binpath, "js", '"') ?>";

View File

@@ -81,8 +81,7 @@ class task_period_ftpPull extends task_appboxAbstract
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
// ... but we could check for safe values (ex. 0 < period < 3600)
?> ?>
<script type="text/javascript"> <script type="text/javascript">
<?php echo $form ?>.proxy.value = "<?php echo p4string::MakeString($sxml->proxy, "js", '"') ?>"; <?php echo $form ?>.proxy.value = "<?php echo p4string::MakeString($sxml->proxy, "js", '"') ?>";

View File

@@ -106,8 +106,7 @@ class task_period_outofdate extends task_abstract
// ==================================================================== // ====================================================================
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
// ... but we could check for safe values
if ((int) ($sxml->period) < 10) { if ((int) ($sxml->period) < 10) {
$sxml->period = 10; $sxml->period = 10;
} elseif ((int) ($sxml->period) > 1440) { // 1 jour } elseif ((int) ($sxml->period) > 1440) { // 1 jour
@@ -489,7 +488,7 @@ class task_period_outofdate extends task_abstract
$ret = self::STATUS_STOPPED; $ret = self::STATUS_STOPPED;
$this->running = false; $this->running = false;
} else { } else {
if (($this->sxTaskSettings = simplexml_load_string($row['settings'])) != FALSE) { if (false !== $this->sxTaskSettings = simplexml_load_string($row['settings'])) {
$period = (int) ($this->sxTaskSettings->period); $period = (int) ($this->sxTaskSettings->period);
if ($period <= 0 || $period >= 24 * 60) { if ($period <= 0 || $period >= 24 * 60) {
$period = 60; $period = 60;

View File

@@ -79,8 +79,7 @@ class task_period_workflow01 extends task_databoxAbstract
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
// ... but we could check for safe values
if ((int) ($sxml->period) < 1) { if ((int) ($sxml->period) < 1) {
$sxml->period = 1; $sxml->period = 1;
} elseif ((int) ($sxml->period) > 1440) { // 1 jour } elseif ((int) ($sxml->period) > 1440) { // 1 jour

View File

@@ -87,8 +87,7 @@ class task_period_writemeta extends task_databoxAbstract
public function xml2graphic($xml, $form) public function xml2graphic($xml, $form)
{ {
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here... if (false !== $sxml = simplexml_load_string($xml)) {
// ... but we could check for safe values (ex. 0 < period < 3600)
if ((int) ($sxml->period) < 10) { if ((int) ($sxml->period) < 10) {
$sxml->period = 10; $sxml->period = 10;
} elseif ((int) ($sxml->period) > 300) { } elseif ((int) ($sxml->period) > 300) {

View File

@@ -22,6 +22,9 @@
<button class="form_submitter single_menu btn btn-inverse" >{% trans 'boutton::refresh' %}</button> <button class="form_submitter single_menu btn btn-inverse" >{% trans 'boutton::refresh' %}</button>
</form> </form>
</td> </td>
<td>
<button type="button" class="delete-account btn btn-danger" value="{{ account.get_id() }}">{% trans 'boutton::supprimer' %}</button>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@@ -83,7 +83,6 @@
{# SCRIPT - HORIZONTAL TABS #} {# SCRIPT - HORIZONTAL TABS #}
<script type ="text/javascript"> <script type ="text/javascript">
$(function() { $(function() {
var pub_tabs = $("#pub_tabs"); var pub_tabs = $("#pub_tabs");
var container = $('#dialog_publicator'); var container = $('#dialog_publicator');
@@ -143,6 +142,45 @@ $(function() {
return false; return false;
}); });
$(".delete-account" , $panel).bind("click", function(){
account_id = $(this).val();
var buttons = {};
buttons[language.valider] = function() {
$.ajax({
type: "POST",
dataType: "json",
url: "/prod/bridge/adapter/" + account_id + "/delete/",
data: {},
success: function(datas){
if(datas.success) {
confirmBox.Close();
publicator_reload_publicator();
} else {
confirmBox.Close();
var alertBox = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
closeButton:true
}, 2);
alertBox.setContent(datas.message);
}
}
});
};
var confirmBox = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
closeButton:true,
cancelButton: true,
buttons: buttons
}, 2);
confirmBox.setContent("{{'You are about to delete this account. Would you like to continue ?'|trans|e('js') }}");
});
$('.form_submitter', $panel).bind('click', function(){ $('.form_submitter', $panel).bind('click', function(){
var $form = $(this).closest('form'); var $form = $(this).closest('form');
var method = $form.attr('method'); var method = $form.attr('method');
@@ -362,13 +400,13 @@ $(function() {
}); });
{% if route.get_count_element_received() == 0 %} {% if route.get_count_element_received() == 0 %}
alert('{% trans "Vous n\'avez selectionne aucun element" %}'); alert('{{ "Vous n\'avez selectionne aucun element"|trans|e('js') }}');
container.dialog('close'); container.dialog('close');
{% elseif route.get_count_actionable() == 0 %} {% elseif route.get_count_actionable() == 0 %}
alert('{% trans "Vous n\'avez pas assez de droits sur les elements selectionnes" %}'); alert('{{ "Vous n\'avez pas assez de droits sur les elements selectionnes"|trans|e('js') }}');
container.dialog('close'); container.dialog('close');
{% elseif route.get_count_actionable() != route.get_count_element_received() %} {% elseif route.get_count_actionable() != route.get_count_element_received() %}
alert('{% trans "Vous n\'avez pas assez de droits sur certains elements selectionnes" %}'); alert('{{ "Vous n\'avez pas assez de droits sur certains elements selectionnes"|trans|e('js') }}');
{% endif %} {% endif %}
}); });
</script> </script>

View File

@@ -237,15 +237,6 @@
{% endif %} {% endif %}
</div> </div>
</div> </div>
<div style="display:none" id="THPD_confirm_del_dlg">
<div id="THPD_confirm_del_dlg_msg">{% trans 'prod::thesaurusTab:dlg:supprimer le terme ?' %}</div>
</div>
<div style="display:none" id="THPD_confirm_accept_dlg">
<div id="THPD_confirm_accept_dlg_msg">{% trans 'prod::thesaurusTab:dlg:accepter le terme ?' %}</div>
</div>
<div style="display:none" id="THPD_confirm_replace_dlg">
<div id="THPD_confirm_replace_dlg_msg">{% trans 'prod::thesaurusTab:dlg:remplacer le terme ?' %}</div>
</div>
</div> </div>
{% endif %} {% endif %}
</div> </div>

View File

@@ -1,4 +1,3 @@
function thesau_show() function thesau_show()
{ {
if(p4.thesau.currentWizard == "???") // first show of thesaurus if(p4.thesau.currentWizard == "???") // first show of thesaurus
@@ -99,12 +98,24 @@ function T_replaceBy2(f)
trees.C._toReplace = { 'sbas':sbas, 'cid':cid, 'replaceby':f }; trees.C._toReplace = { 'sbas':sbas, 'cid':cid, 'replaceby':f };
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:Remplacement du candidat "%s" :' %}', term) ; {% set message %}
msg += "<br/><br/>"; {% trans 'prod::thesaurusTab:dlg:Remplacement du candidat "%(from)s" par "%(to)s"' %}
msg += $.sprintf('{% trans 'prod::thesaurusTab:dlg:Remplacer par "%s"' %}', f) ; {% endset %}
$("#THPD_confirm_replace_dlg_msg").html(msg); var msg = $.sprintf("{{ message | e('js') }}", {'from':term, 'to':f});
$("#THPD_confirm_replace_dlg").dialog('open');
var confirmBox = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
cancelButton: true,
buttons: {
"Ok" : function() {
confirmBox.Close();
T_replaceCandidates_OK();
}
}
});
confirmBox.setContent(msg);
} }
@@ -160,9 +171,6 @@ function T_filter_delayed2(f, delay, mode)
} }
}); });
} }
} }
else if(mode=='CANDIDATE') else if(mode=='CANDIDATE')
@@ -213,27 +221,23 @@ function T_filter_delayed2(f, delay, mode)
// ====================================================================================================== // ======================================================================================================
function T_replaceCandidates_OK()
function T_replaceCandidates_OK(dlgnode)
{ {
$("#THPD_confirm_replace_dlg_msg").html("{% trans 'prod::thesaurusTab:dlg:Remplacement en cours.' %}"); {% set replaceing_msg %}
{% trans 'prod::thesaurusTab:dlg:Remplacement en cours.' %}
// 3 cases {% endset %}
// the new term already exists (possibly many times) in the thesaurus
// the new term already exists in the candidates
// the new term is brand new
// the simpliest solution is to replace the terms and let the indexer work
var replacingBox = p4.Dialog.Create({
size : 'Alert'
});
replacingBox.setContent("{{ replaceing_msg | e('js') }}");
var parms = { var parms = {
url: "/xmlhttp/replacecandidate.j.php", url: "/xmlhttp/replacecandidate.j.php",
data: { data: {
"sbid" : trees.C._toReplace.sbas "id[]" : trees.C._toReplace.sbas + "." + trees.C._toReplace.cid
, "cid" : trees.C._toReplace.cid , "t" : trees.C._toReplace.replaceby
, "t" : trees.C._toReplace.replaceby , "debug" : '0'
// , "debug" : '1'
}, },
async: false, async: false,
cache: false, cache: false,
@@ -243,7 +247,25 @@ function T_replaceCandidates_OK(dlgnode)
{ {
trees.C._toReplace = null; trees.C._toReplace = null;
thesauShowWizard("wiz_0", false); thesauShowWizard("wiz_0", false);
$(dlgnode).dialog("close");
replacingBox.Close();
if(result.msg != '')
{
var alert = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
closeButton:true
});
alert.setContent(result.msg);
}
for(i in result.ctermsDeleted)
{
var cid = "#CX_P\\." + result.ctermsDeleted[i].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery
$(cid).remove();
}
}, },
_ret: null // private alchemy _ret: null // private alchemy
}; };
@@ -252,9 +274,16 @@ function T_replaceCandidates_OK(dlgnode)
} }
function T_acceptCandidates_OK(dlgnode) function T_acceptCandidates_OK()
{ {
$("#THPD_confirm_accept_dlg_msg").html("{% trans 'prod::thesaurusTab:dlg:Acceptation en cours.' %}"); {% set accepting_msg %}
{% trans 'prod::thesaurusTab:dlg:Acceptation en cours.' %}
{% endset %}
var acceptingBox = p4.Dialog.Create({
size : 'Alert'
});
acceptingBox.setContent("{{ accepting_msg | e('js') }}");
var t_ids = []; var t_ids = [];
var dst = trees.C._toAccept.dst.split('.'); var dst = trees.C._toAccept.dst.split('.');
@@ -264,20 +293,19 @@ function T_acceptCandidates_OK(dlgnode)
same_sbas = true; same_sbas = true;
// obviously the candidates and the target already complies (same sbas, good tbranch) // obviously the candidates and the target already complies (same sbas, good tbranch)
trees.C._selInfos.sel.each( trees.C._selInfos.sel.each(
function() function()
{ {
var x = this.getAttribute('id').split('.'); var x = this.getAttribute('id').split('.');
x.shift(); x.shift();
if(x.shift() != sbid) if(x.shift() != sbid)
same_sbas = false; same_sbas = false;
t_ids.push(x.join('.')); t_ids.push(x.join('.'));
} }
); );
if(!same_sbas) if(!same_sbas)
return; return;
var parms = { var parms = {
url: "/xmlhttp/acceptcandidates.j.php", url: "/xmlhttp/acceptcandidates.j.php",
data: { data: {
@@ -313,17 +341,15 @@ function T_acceptCandidates_OK(dlgnode)
+ j.parm['id'].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery + j.parm['id'].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery
$(z).replaceWith(j.html); $(z).replaceWith(j.html);
trees.C._toAccept = null;
thesauShowWizard("wiz_0",false);
$(dlgnode).dialog("close");
} }
, "json"); , "json");
} }
trees.C._toAccept = null;
// $("#THPD_confirm_accept_dlg_msg").dialog("close"); thesauShowWizard("wiz_0",false);
acceptingBox.Close();
}, },
error:function(){}, error:function(){acceptingBox.Close();},
timeout:function(){}, timeout:function(){acceptingBox.Close();},
_ret: null // private alchemy _ret: null // private alchemy
}; };
@@ -333,20 +359,27 @@ function T_acceptCandidates_OK(dlgnode)
function C_deleteCandidates_OK() function C_deleteCandidates_OK()
{ {
$("#THPD_confirm_del_dlg_msg").html("{% trans 'prod::thesaurusTab:dlg:Suppression en cours.' %}"); {% set deleting_msg %}
{% trans 'prod::thesaurusTab:dlg:Suppression en cours.' %}
{% endset %}
var deletingBox = p4.Dialog.Create({
size : 'Alert'
});
deletingBox.setContent("{{ deleting_msg | e('js') }}");
var t_ids = []; var t_ids = [];
var lisel = trees.C.tree.find("LI .selected"); var lisel = trees.C.tree.find("LI .selected");
trees.C.tree.find("LI .selected").each( trees.C.tree.find("LI .selected").each(
function() function()
{ {
var x = this.getAttribute('id').split('.'); var x = this.getAttribute('id').split('.');
x.shift(); x.shift();
t_ids.push(x.join('.')); t_ids.push(x.join('.'));
} }
); );
var parms = { var parms = {
url:"/xmlhttp/deletecandidates.j.php", url:"/xmlhttp/replacecandidate.j.php",
data:{"id[]":t_ids}, data:{"id[]":t_ids},
async:false, async:false,
cache:false, cache:false,
@@ -354,12 +387,23 @@ function C_deleteCandidates_OK()
timeout:10*60*1000, // 10 minutes ! timeout:10*60*1000, // 10 minutes !
success: function(result, textStatus) success: function(result, textStatus)
{ {
for(i in result) deletingBox.Close();
if(result.msg != '')
{ {
var cid = "#CX_P\\." + result[i].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery var alert = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
closeButton:true
});
alert.setContent(result.msg);
}
for(i in result.ctermsDeleted)
{
var cid = "#CX_P\\." + result.ctermsDeleted[i].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery
$(cid).remove(); $(cid).remove();
} }
$("#THPD_confirm_del_dlg").dialog("close");
}, },
_ret: null _ret: null
}; };
@@ -379,23 +423,41 @@ function T_acceptCandidates(menuItem, menu, type)
if(lisel.length == 0) if(lisel.length == 0)
return; return;
{% set messageOne %}
{% trans 'prod::thesaurusTab:dlg:accepter le terme candidat "%s" ?' %}
{% endset %}
{% set messageMany %}
{% trans 'prod::thesaurusTab:dlg:accepter les %d termes candidats ?' %}
{% endset %}
var msg; var msg;
if(lisel.length > 1)
if(lisel.length == 1)
{ {
msg = $.sprintf("{% trans 'prod::thesaurusTab:dlg:accepter les %d termes candidats ?' %}", lisel.length); var term = lisel.eq(0).find("span span").html();
msg = $.sprintf("{{ messageOne | e('js') }}", term);
} }
else else
{ {
var term = lisel.eq(0).find("span span").html(); msg = $.sprintf("{{ messageMany | e('js') }}", lisel.length);
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:accepter le terme candidat "%s" ?' %}', term);
} }
trees.C._toAccept.type = type; trees.C._toAccept.type = type;
trees.C._toAccept.dst = lidst.eq(0).attr("id"); trees.C._toAccept.dst = lidst.eq(0).attr("id");
$("#THPD_confirm_accept_dlg_msg").html(msg); var confirmBox = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
cancelButton: true,
buttons: {
"Ok" : function() {
confirmBox.Close();
T_acceptCandidates_OK();
}
}
});
confirmBox.setContent(msg);
$("#THPD_confirm_accept_dlg").dialog('open');
} }
@@ -459,13 +521,21 @@ function C_MenuOption(menuItem, menu, option, parm)
// display helpful message into the thesaurus box... // display helpful message into the thesaurus box...
var msg; var msg;
if(trees.C._selInfos.n > 1)
{% set messageOne %}
{% trans 'prod::thesaurusTab:wizard:clic-droit / accepter le terme candidat "%s"' %}
{% endset %}
{% set messageMany %}
{% trans "prod::thesaurusTab:wizard:clic-droit / accepter les %s termes candidats" %}
{% endset %}
if(trees.C._selInfos.n == 1)
{ {
msg = $.sprintf("{% trans 'prod::thesaurusTab:wizard:clic-droit / accepter les %s termes candidats' %}", trees.C._selInfos.n); msg = $.sprintf("{{ messageOne | e }}", menu._srcElement.find("span").html());
} }
else else
{ {
msg = $.sprintf('{% trans 'prod::thesaurusTab:wizard:clic-droit / accepter le terme candidat "%s"' %}', menu._srcElement.find("span").html()); msg = $.sprintf("{{ messageMany | e }}", trees.C._selInfos.n);
} }
// set the content of the wizard // set the content of the wizard
@@ -479,14 +549,22 @@ function C_MenuOption(menuItem, menu, option, parm)
case 'REPLACE': case 'REPLACE':
// display helpful message into the thesaurus box... // display helpful message into the thesaurus box...
var msg; var msg;
if(trees.C._selInfos.n > 1)
{% set messageOne %}
{% trans "prod::thesaurusTab:dlg:remplacer le terme "%s" des fiches par :" %}
{% endset %}
{% set messageMany %}
{% trans "prod::thesaurusTab:dlg:remplacer les %d termes des fiches par :" %}
{% endset %}
if(trees.C._selInfos.n == 1)
{ {
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:remplacer les %d termes des fiches par :' %}', trees.C._selInfos.n); var term = trees.C._selInfos.sel.eq(0).find("span span").html();
msg = $.sprintf('{{ messageOne | e }}', term);
} }
else else
{ {
var term = trees.C._selInfos.sel.eq(0).find("span span").html(); msg = $.sprintf('{{ messageMany |e }}', trees.C._selInfos.n);
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:remplacer le terme "%s" des fiches par :' %}', term);
} }
p4.thesau.tabs.tabs('select', 0); p4.thesau.tabs.tabs('select', 0);
@@ -501,27 +579,43 @@ function C_MenuOption(menuItem, menu, option, parm)
case 'DELETE': case 'DELETE':
$("#THPD_WIZARDS DIV", p4.thesau.tabs).hide(); $("#THPD_WIZARDS DIV", p4.thesau.tabs).hide();
// display helpful message into the thesaurus box... // display helpful message into the thesaurus box...
var msg;
if(trees.C._selInfos.n > 1) {% set messageOne %}
{% trans 'prod::thesaurusTab:dlg:supprimer le terme "%s" des fiches ?' %}
{% endset %}
{% set messageMany %}
{% trans 'prod::thesaurusTab:dlg:supprimer les %d termes des fiches ?' %}
{% endset %}
var msg;
if(trees.C._selInfos.n == 1)
{ {
msg = $.sprintf("{% trans 'prod::thesaurusTab:dlg:supprimer les %d termes des fiches ?' %}", trees.C._selInfos.n); var term = trees.C._selInfos.sel.eq(0).find("span span").html();
msg = $.sprintf("{{ messageOne | e('js') }}", term);
} }
else else
{ {
var term = trees.C._selInfos.sel.eq(0).find("span span").html(); msg = $.sprintf("{{ messageMany | e('js') }}", trees.C._selInfos.n);
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:supprimer le terme "%s" des fiches ?' %}', term);
} }
$("#THPD_confirm_del_dlg_msg").html(msg); var confirmBox = p4.Dialog.Create({
size : 'Alert',
$("#THPD_confirm_del_dlg").dialog('open'); closeOnEscape : true,
cancelButton: true,
buttons: {
"Ok" : function() {
confirmBox.Close();
C_deleteCandidates_OK();
}
}
});
confirmBox.setContent(msg);
break; break;
} }
} }
function Xclick(e) function Xclick(e)
{ {
var x = e.srcElement ? e.srcElement : e.target; var x = e.srcElement ? e.srcElement : e.target;
@@ -662,14 +756,16 @@ function CXdblClick(e)
{ {
case "SPAN": // term case "SPAN": // term
var li = $(x).closest('li'); var li = $(x).closest('li');
var tid = li.attr('id'); var field = li.closest('[field]').attr('field');
if(tid.substr(0,5)=="CX_P.") if(typeof(field) != "undefined")
{ {
var sbid = tid.split(".")[1]; var tid = li.attr('id');
var term = $(x).text(); if(tid.substr(0,5)=="CX_P.")
var field = li.closest('[field]').attr('field'); {
var sbid = tid.split(".")[1];
doThesSearch('C', sbid, term, field); var term = $(x).text();
doThesSearch('C', sbid, term, field);
}
} }
break; break;
default: default:
@@ -718,12 +814,6 @@ function doThesSearch(type, sbid, term, field)
} }
function thesau_clickThesaurus(event) // onclick dans le thesaurus function thesau_clickThesaurus(event) // onclick dans le thesaurus
{ {
// on cherche ou on a clique // on cherche ou on a clique
@@ -828,7 +918,7 @@ function replaceEditSel(value)
{ {
if(!p4.thesau.lastTextfocus || !p4.thesau.lastTextfocus.selectedTerm) if(!p4.thesau.lastTextfocus || !p4.thesau.lastTextfocus.selectedTerm)
return; return;
// alert(textarea.selectedTerm.start + " ; " + textarea.selectedTerm.end);
p4.thesau.lastTextfocus.value = p4.thesau.lastTextfocus.value.substr(0, p4.thesau.lastTextfocus.selectedTerm.start) + value + p4.thesau.lastTextfocus.value.substr(p4.thesau.lastTextfocus.selectedTerm.end); p4.thesau.lastTextfocus.value = p4.thesau.lastTextfocus.value.substr(0, p4.thesau.lastTextfocus.selectedTerm.start) + value + p4.thesau.lastTextfocus.value.substr(p4.thesau.lastTextfocus.selectedTerm.end);
if(typeof(document.selection) != 'undefined') if(typeof(document.selection) != 'undefined')
{ {
@@ -922,7 +1012,7 @@ function ThesauThesaurusSeeker(sbas_id)
}); });
}; };
this.xmlhttpstatechanged = function(ret, id) { this.xmlhttpstatechanged = function(ret, id) {
try try
{ {
if(!this.tObj["TH_searching"]) if(!this.tObj["TH_searching"])
@@ -1113,10 +1203,6 @@ function startThesaurus(){
p4.thesau.lastClickedCandidate = null; p4.thesau.lastClickedCandidate = null;
// $("#THPD_confirm_del_dlg").remove();
// $("#THPD_confirm_accept_dlg").remove();
// $("#THPD_confirm_replace_dlg").remove();
p4.thesau.tabs = $("#THPD_tabs"); p4.thesau.tabs = $("#THPD_tabs");
p4.thesau.tabs.tabs(); p4.thesau.tabs.tabs();
@@ -1132,63 +1218,6 @@ function startThesaurus(){
} }
}; };
$("#THPD_confirm_del_dlg").dialog( {
modal:true,
autoOpen:false,
buttons:{
"{% trans 'boutton::ok' %}":function()
{
C_deleteCandidates_OK();
},
"{% trans 'boutton::annuler' %}":function()
{
$(this).dialog("close");
}
}
}
);
$("#THPD_confirm_accept_dlg").dialog( {
closeOnEscape:true,
resizable:false,
draggable:false,
modal:true,
autoOpen:false,
buttons:{
"{% trans 'prod::thesaurusTab:dlg:OK' %}":function()
{
T_acceptCandidates_OK(this);
},
"{% trans 'prod::thesaurusTab:dlg:Annuler' %}":function()
{
$(this).dialog("close");
}
}
}
);
$("#THPD_confirm_replace_dlg").dialog( {
closeOnEscape:true,
resizable:false,
draggable:false,
modal:true,
autoOpen:false,
buttons:{
"{% trans 'prod::thesaurusTab:dlg:OK' %}":function()
{
T_replaceCandidates_OK(this);
},
"{% trans 'prod::thesaurusTab:dlg:Annuler' %}":function()
{
$(this).dialog("close");
}
}
}
);
trees.T.tree.contextMenu( trees.T.tree.contextMenu(
[ [
{ {
@@ -1290,7 +1319,7 @@ function startThesaurus(){
{% endfor %} {% endfor %}
{ {
label:'{% trans 'prod::thesaurusTab:cmenu:Remplacer par...' %}', label:'{% trans 'prod::thesaurusTab:cmenu:Remplacer par...' %}',
disabled:true, // disabled:true,
onclick:function(menuItem, menu) onclick:function(menuItem, menu)
{ {
C_MenuOption(menuItem, menu, 'REPLACE', null); C_MenuOption(menuItem, menu, 'REPLACE', null);
@@ -1298,7 +1327,7 @@ function startThesaurus(){
}, },
{ {
label:'{% trans 'boutton::supprimer' %}', label:'{% trans 'boutton::supprimer' %}',
disabled:true, // disabled:true,
onclick:function(menuItem, menu) onclick:function(menuItem, menu)
{ {
C_MenuOption(menuItem, menu, 'DELETE', null); C_MenuOption(menuItem, menu, 'DELETE', null);
@@ -1341,6 +1370,16 @@ function startThesaurus(){
// glue selection info to the tree // glue selection info to the tree
trees.C._selInfos = {'sel':lisel, 'field':field, 'sbas':sbas, 'n':lisel.length} ; trees.C._selInfos = {'sel':lisel, 'field':field, 'sbas':sbas, 'n':lisel.length} ;
// $(this.menu).find('.context-menu-item')[{{ thesau_languages|length }}].addClass('context-menu-item-disabled');
if(lisel.length == 1)
{
$(this.menu).find('.context-menu-item').eq({{ thesau_languages|length }}).removeClass('context-menu-item-disabled');
}
else
{
$(this.menu).find('.context-menu-item').eq({{ thesau_languages|length }}).addClass('context-menu-item-disabled');
}
} }
else else
{ {

View File

@@ -388,4 +388,23 @@ class BridgeApplication extends PhraseanetWebTestCaseAuthenticatedAbstract
$response = self::$DI['client']->getResponse(); $response = self::$DI['client']->getResponse();
$this->assertTrue($response->isRedirect()); $this->assertTrue($response->isRedirect());
} }
public function testDeleteAccount()
{
$account = Bridge_Account::create(appbox::get_instance(\bootstrap::getCore()), self::$api, self::$user, 'hello', 'you');
$url = "/bridge/adapter/" . $account->get_id() . "/delete/";
$this->client->request('POST', $url);
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
$datas = json_decode($response->getContent(), true);
$this->assertArrayHasKey('success', $datas);
$this->assertTrue($datas['success']);
try {
\Bridge_Account::load_account(appbox::get_instance(\bootstrap::getCore()), $account->get_id());
$this->fail('Account is not deleted');
} catch(Bridge_Exception_AccountNotFound $e) {
}
unset($account, $response);
}
} }

View File

@@ -1,162 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2012 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Alchemy\Phrasea\Application;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
require_once __DIR__ . "/../../lib/bootstrap.php";
$app = new Application();
$request = http_request::getInstance();
$parm = $request->get_parms(
'id'
);
$tsbas = array();
$ret = array();
$conn = connection::getPDOConnection($app);
$unicode = new unicode();
$sql = "SELECT * FROM sbas";
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) {
$tsbas['b' . $row['sbas_id']] = array('sbas' => $row, 'tids' => array());
}
foreach ($parm['id'] as $id) {
$id = explode('.', $id);
$sbas = array_shift($id);
if (array_key_exists('b' . $sbas, $tsbas))
$tsbas['b' . $sbas]['tids'][] = implode('.', $id);
}
foreach ($tsbas as $sbas) {
if (count($sbas['tids']) <= 0)
continue;
$databox = $app['phraseanet.appbox']->get_databox((int) $sbas['sbas']['sbas_id']);
try {
$connbas = connection::getPDOConnection($app, $sbas['sbas']['sbas_id']);
} catch (Exception $e) {
continue;
}
$domth = $databox->get_dom_thesaurus();
$domct = $databox->get_dom_cterms();
if ( ! $domth || ! $domct)
continue;
$lid = '';
$tsyid = array();
$xpathct = new DOMXPath($domct);
foreach ($sbas['tids'] as $tid) {
$xp = '//te[@id="' . $tid . '"]/sy';
$nodes = $xpathct->query($xp);
if ($nodes->length == 1) {
$sy = $term = $nodes->item(0);
$w = $sy->getAttribute('w');
$syid = str_replace('.', 'd', $sy->getAttribute('id')) . 'd';
$lid .= ( $lid ? ',' : '') . "'" . $syid . "'";
$tsyid[$syid] = array('w' => $w, 'field' => $sy->parentNode->parentNode->getAttribute('field'));
// remove candidate from cterms
$te = $sy->parentNode;
$te->parentNode->removeChild($te);
}
}
$databox->saveCterms($domct);
$sql = 'SELECT t.record_id, r.xml, t.value
FROM thit AS t
INNER JOIN record AS r USING(record_id)
WHERE value IN (' . $lid . ') ORDER BY record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$t_rid = array();
foreach ($rs as $rowbas) {
$rid = $rowbas['record_id'];
if ( ! array_key_exists('' . $rid, $t_rid))
$t_rid['' . $rid] = array('xml' => $rowbas['xml'], 'hits' => array());
$t_rid['' . $rid]['hits'][] = $rowbas['value'];
}
foreach ($t_rid as $rid => $record) {
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
if ( ! ($dom->loadXML($record['xml'])))
continue;
$nodetodel = array();
$xp = new DOMXPath($dom);
foreach ($record['hits'] as $value) {
$field = $tsyid[$value];
$x = '/record/description/' . $field['field'];
$nodes = $xp->query($x);
foreach ($nodes as $n) {
$current_value = $unicode->remove_indexer_chars($n->textContent);
if ($current_value == $field['w']) {
$nodetodel[] = $n;
}
}
}
foreach ($nodetodel as $n) {
$n->parentNode->removeChild($n);
}
$sql = 'DELETE FROM idx WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'DELETE FROM prop WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'DELETE FROM thit WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'UPDATE record
SET status=(status & ~3)|4, jeton=' . (JETON_WRITE_META_DOC | JETON_WRITE_META_SUBDEF) . ',
xml = :xml WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid, ':xml' => $dom->saveXML()));
$stmt->closeCursor();
}
}
$ret = $parm['id'];
/**
* @todo respecter les droits d'editing par collections
*/
phrasea::headers(200, true, 'application/json', 'UTF-8', false);
print(p4string::jsonencode($ret));

View File

@@ -21,229 +21,238 @@ $app = new Application();
$request = http_request::getInstance(); $request = http_request::getInstance();
$parm = $request->get_parms( $parm = $request->get_parms(
'sbid' 'id',
, 'cid' // candidate (id) to replace 't',
, 't' // replacing term 'debug'
, 'debug'
); );
phrasea::headers(200, true, 'application/json', 'UTF-8', false); phrasea::headers(200, true, 'application/json', 'UTF-8', false);
if ($parm['debug']) define('SEARCH_REPLACE_MAXREC', 25);
print("<pre>");
$dbname = null; $tsbas = array();
$result = array('n_recsChanged' => 0); // , 'n_termsDeleted'=>0, 'n_termsReplaced'=>0); $ret = array(
'ctermsDeleted'=>array(),
'maxRecsUpdatable'=>SEARCH_REPLACE_MAXREC,
'nRecsToUpdate'=>0,
'nRecsUpdated'=>0,
'msg'=>''
);
try {
$databox = $app['phraseanet.appbox']->get_databox((int) $parm['sbid']); foreach ($parm['id'] as $id) {
$domth = $databox->get_dom_thesaurus(); $id = explode('.', $id);
$domct = $databox->get_dom_cterms(); $sbas_id = array_shift($id);
if (!array_key_exists('b' . $sbas_id, $tsbas)) {
$tsbas['b' . $sbas_id] = array(
'sbas_id' => (int) $sbas_id,
'tids' => array(),
'domct' => null,
'tvals' => array(),
'lid' => '',
'trids' => array()
);
}
$tsbas['b' . $sbas_id]['tids'][] = implode('.', $id);
}
if ($domth && $domct) { if ($parm['debug']) {
$xpathct = new DOMXPath($domct); var_dump($tsbas);
}
$field = null; $appbox = $app['phraseanet.appbox'];
$x = null;
$xp = '//te[@id="' . $parm['cid'] . '"]/sy';
// first, count the number of records to update
foreach ($tsbas as $ksbas=>$sbas) {
/* @var $databox databox */
try {
$databox = $appbox->get_databox($sbas['sbas_id']);
$connbas = $databox->get_connection();
// $domth = $databox->get_dom_thesaurus();
$tsbas[$ksbas]['domct'] = $databox->get_dom_cterms();
} catch (Exception $e) {
continue;
}
if ( ! $tsbas[$ksbas]['domct']) {
continue;
}
$lid = '';
$xpathct = new DOMXPath($tsbas[$ksbas]['domct']);
foreach ($sbas['tids'] as $tid) {
$xp = '//te[@id="' . $tid . '"]/sy';
$nodes = $xpathct->query($xp); $nodes = $xpathct->query($xp);
if ($nodes->length == 1) { if ($nodes->length == 1) {
$sy = $term = $nodes->item(0); $sy = $term = $nodes->item(0);
$candidate = array('a' => $sy->getAttribute('v'), 'u' => $sy->getAttribute('w'));
if (($k = $sy->getAttribute('k')))
$candidate['u'] .= ' (' . $k . ')';
if ($parm['debug'])
printf("%s : candidate = %s \n", __LINE__, var_export($candidate, true));
$syid = str_replace('.', 'd', $sy->getAttribute('id')) . 'd'; $syid = str_replace('.', 'd', $sy->getAttribute('id')) . 'd';
$lid .= ( $lid ? ',' : '') . "'" . $syid . "'";
$field = $sy->parentNode->parentNode->getAttribute('field'); $field = $sy->parentNode->parentNode->getAttribute('field');
// remove candidate from cterms if ( ! array_key_exists($field, $tsbas[$ksbas]['tvals'])) {
$te = $sy->parentNode; $tsbas[$ksbas]['tvals'][$field] = array();
$te->parentNode->removeChild($te);
$databox->saveCterms($domct);
$sql = 'SELECT t.record_id, r.xml
FROM thit AS t INNER JOIN record AS r USING(record_id)
WHERE t.value = :syn_id
ORDER BY record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':syn_id' => $syid));
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($parm['debug'])
printf("%s : %s \n", __LINE__, $sql);
$t_rid = array();
foreach ($rs as $rowbas) {
$rid = $rowbas['record_id'];
if ( ! array_key_exists('' . $rid, $t_rid))
$t_rid['' . $rid] = $rowbas['xml'];
} }
if ($parm['debug']) $tsbas[$ksbas]['tvals'][$field][] = $sy;
printf("%s : %s \n", __LINE__, var_export($t_rid, true)); }
}
$replacing = array(); if ($lid == '') {
$parm['t'] = explode(';', $parm['t']); // no cterm was found
foreach ($parm['t'] as $t) continue;
$replacing[] = simplified($t); }
if ($parm['debug']) $tsbas[$ksbas]['lid'] = $lid;
printf("%s : replacing=%s \n", __LINE__, var_export($replacing, true));
// count records
$sql = 'SELECT DISTINCT record_id AS r'
.' FROM thit WHERE value IN (' . $lid . ') ORDER BY record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute();
if ($parm['debug']) {
printf("(%d) sql: \n", __LINE__);
var_dump($sql);
}
$tsbas[$ksbas]['trids'] = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$stmt->closeCursor();
$ret['nRecsToUpdate'] += count($tsbas[$ksbas]['trids']);
}
foreach ($t_rid as $rid => $xml) { if ($parm['debug']) {
if ($parm['debug']) printf("(%d) nRecsToUpdate = %d \ntsbas: \n", __LINE__, $ret['nRecsToUpdate']);
printf("%s rid=%s \n", __LINE__, $rid); print_r($tsbas);
$dom = new DOMDocument(); }
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
if ( ! ($dom->loadXML($xml)))
continue;
if ($parm['debug'])
printf("AVANT:\n%s \n", htmlentities($dom->saveXML()));
// $existed = false; if($ret['nRecsToUpdate'] <= SEARCH_REPLACE_MAXREC)
$nodetoreplace = null; {
$nodestodelete = array(); $unicode = new unicode;
$xp = new DOMXPath($dom); foreach ($tsbas as $sbas) {
$x = '/record/description/' . $field; /* @var $databox databox */
if ($parm['debug']) try {
printf("%s x=%s \n", __LINE__, $x); $databox = $appbox->get_databox($sbas['sbas_id']);
$nodes = $xp->query($x); $connbas = $databox->get_connection();
} catch (Exception $e) {
continue;
}
$insertBefore = null; // fix caption of records
if ($nodes->length <= 0) foreach ($sbas['trids'] as $rid) {
continue;
// {
$insertBefore = $nodes->item($nodes->length - 1);
if ($parm['debug'])
printf("%s nodes->length=%s - insertBefore=%s, nn=%s\n", __LINE__, $nodes->length, var_export($insertBefore, true), $insertBefore->nodeName);
while (($insertBefore = $insertBefore->nextSibling) && $insertBefore->nodeType != XML_ELEMENT_NODE);
if ($parm['debug'] && $insertBefore)
printf("%s insertBefore=%s , nn=%s \n", __LINE__, var_export($insertBefore, true), $insertBefore->nodeName);
$t_mval = array(); if ($parm['debug']) {
foreach ($nodes as $n) { printf("(%d) ======== working on record_id = %d ======= \n", __LINE__, $rid);
$value = simplified($n->textContent); }
if (in_array($value['a'], $t_mval)) // a chance to delete doubles try {
continue; $record = $databox->get_record($rid);
for ($i = 0; $i < 9999 && array_key_exists($value['u'] . '_' . $i, $t_mval); $i ++ )
;
$t_mval[$value['u'] . '_' . $i] = $value['a'];
$nodestodelete[] = $n;
}
if ($parm['debug'])
printf("%s : t_mval AVANT = %s \n", __LINE__, var_export($t_mval, true));
if (($k = array_search($candidate['a'], $t_mval)) !== false) { $metadatask = array(); // datas to keep
unset($t_mval[$k]); $metadatasd = array(); // datas to delete
if ($parm['debug'])
printf("%s : after unset %s from t_mval %s \n", __LINE__, $k, var_export($t_mval, true)); /* @var $field caption_field */
foreach ($replacing as $r) { foreach ($record->get_caption()->get_fields(null, true) as $field) {
if (in_array($r['a'], $t_mval)) $meta_struct_id = $field->get_meta_struct_id();
continue; if ($parm['debug']) {
for ($i = 0; $i < 9999 && array_key_exists($r['u'] . '_' . $i, $t_mval); $i ++ ) printf("(%d) field '%s' meta_struct_id=%s \n", __LINE__, $field->get_name(), $meta_struct_id);
; }
$t_mval[$r['u'] . '_' . $i] = $r['a'];
/* @var $v caption_Field_Value */
$fname = $field->get_name();
if(!array_key_exists($fname, $sbas['tvals'])) {
foreach ($field->get_values() as $v) {
if ($parm['debug']) {
printf("(%d) ...v = '%s' (meta_id=%s) keep \n", __LINE__, $v->getValue(), $v->getId());
}
$metadatask[] = array(
'meta_struct_id' => $meta_struct_id,
'meta_id' => $v->getId(),
'value' => $v->getValue()
);
}
}
else {
foreach ($field->get_values() as $v) {
$keep = true;
$vtxt = $unicode->remove_indexer_chars($v->getValue());
foreach($sbas['tvals'][$fname] as $sy) {
if ($sy->getAttribute('w') == $vtxt) {
$keep = false;
}
}
if ($parm['debug']) {
printf("(%d) ...v = '%s' (meta_id=%s) %s \n", __LINE__, $v->getValue(), $v->getId(), ($keep ? '' : '!!! drop !!!'));
}
if ($keep) {
$metadatask[] = array(
'meta_struct_id' => $meta_struct_id,
'meta_id' => $v->getId(),
'value' => $v->getValue()
);
} else {
$metadatasd[] = array(
'meta_struct_id' => $meta_struct_id,
'meta_id' => $v->getId(),
'value' => $parm['t'] ? $parm['t'] : ''
);
}
}
} }
if ($parm['debug'])
printf("%s : after replace to t_mval %s \n", __LINE__, var_export($t_mval, true));
} }
foreach ($nodestodelete as $n) if ($parm['debug']) {
$n->parentNode->removeChild($n); printf("(%d) metadatask: \n", __LINE__);
var_dump($metadatask);
ksort($t_mval, SORT_STRING); printf("(%d) metadatasd: \n", __LINE__);
var_dump($metadatasd);
if ($insertBefore) {
array_reverse($t_mval);
foreach ($t_mval as $t)
$insertBefore->parentNode->insertBefore($dom->createElement($field), $insertBefore)->appendChild($dom->createTextNode($t));
} else {
$desc = $xp->query('/record/description')->item(0);
foreach ($t_mval as $t)
$desc->appendChild($dom->createElement($field))->appendChild($dom->createTextNode($t));
} }
if(count($metadatasd) > 0) {
if ($parm['debug']) if ( ! $parm['debug']) {
printf("%s : t_mval APRES = %s \n", __LINE__, var_export($t_mval, true)); $record->set_metadatas($metadatasd, true);
$ret['nRecsUpdated']++;
}
if ($parm['debug'])
printf("APRES:\n%s \n", htmlentities($dom->saveXML()));
if ( ! $parm['debug']) {
$sql = 'DELETE FROM idx WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'DELETE FROM prop WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'DELETE FROM thit WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid));
$stmt->closeCursor();
$sql = 'UPDATE record
SET status=(status & ~3)|4, jeton=' . (JETON_WRITE_META_DOC | JETON_WRITE_META_SUBDEF) . '
, xml = :xml
WHERE record_id = :record_id';
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $rid, ':xml' => $dom->saveXML()));
$stmt->closeCursor();
} }
$result['n_recsChanged'] ++; } catch (\Exception $e) {
continue;
} }
} }
}
} catch (Exception $e) {
} // delete the branch from the cterms
if ($parm['debug']) {
function simplified($t) printf("cterms before :\n%s \n", $sbas['domct']->saveXML());
{ }
$t = splitTermAndContext($t); foreach($sbas['tvals'] as $tval) {
$unicode = new unicode(); foreach($tval as $sy) {
$su = $unicode->remove_indexer_chars($sa = $t[0]); // remove candidate from cterms
if ($t[1]) { $te = $sy->parentNode;
$sa .= ' (' . ($t[1]) . ')'; $te->parentNode->removeChild($te);
$su .= ' (' . $unicode->remove_indexer_chars($t[1]) . ')'; $ret['ctermsDeleted'][] = $sbas['sbas_id'] . '.' . $te->getAttribute('id');
} }
}
return(array('a' => $sa, 'u' => $su)); if ($parm['debug']) {
} printf("cterms after :\n%s \n", $sbas['domct']->saveXML());
print(p4string::jsonencode(array('parm' => $parm, 'result' => $result))); }
if ( ! $parm['debug']) {
if ($parm['debug']) $databox->saveCterms($sbas['domct']);
print("</pre>");
function splitTermAndContext($word)
{
$term = trim($word);
$context = '';
if (($po = strpos($term, '(')) !== false) {
if (($pc = strpos($term, ')', $po)) !== false) {
$context = trim(substr($term, $po + 1, $pc - $po - 1));
$term = trim(substr($term, 0, $po));
} else {
$context = trim(substr($term, $po + 1));
$term = trim(substr($term, 0, $po));
} }
}
return(array($term, $context)); }
$ret['msg'] = sprintf(_('prod::thesaurusTab:dlg:%d record(s) updated'), $ret['nRecsUpdated']);
} }
else {
// too many records to update
$ret['msg'] = sprintf(_('prod::thesaurusTab:dlg:too many (%1$d) records to update (limit=%2$d)'), $ret['nRecsToUpdate'], SEARCH_REPLACE_MAXREC);
}
/**
* @todo respecter les droits d'editing par collections
*/
print(p4string::jsonencode($ret));