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() . '/');
})->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) {
$page = max((int) $app['request']->query->get('page'), 0);
$quantity = 10;

View File

@@ -88,7 +88,7 @@ class Prod extends Helper
continue;
}
if (simplexml_load_string($databox->get_cterms())) {
if (false !== simplexml_load_string($databox->get_cterms())) {
$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());
$vn = "";
if ($str = simplexml_load_string($collection->get_prefs()))
if (false !== $str = simplexml_load_string($collection->get_prefs())) {
$vn = (string) ($str->pdfPrintappear);
}
if ($vn == "" || $vn == "1") {
$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);
libxml_clear_errors();
if ( ! $xml) {
if (false === $xml) {
return false;
}
@@ -723,10 +723,9 @@ class Bridge_Api_Youtube extends Bridge_Api_Abstract implements Bridge_Api_Inter
$cat = array();
$url_cat = sprintf('%s?hl=%s', self::CATEGORY_URL, $this->get_locale());
$cxml = @simplexml_load_file($url_cat);
if ( ! $cxml)
if (false === $cxml = simplexml_load_file($url_cat)) {
throw new Bridge_Exception_ApiConnectorRequestFailed('Failed to retrive youtube categories');
}
$cxml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
$categories = $cxml->xpath('//atom:category');

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -35,8 +35,8 @@ class queries
}
$cssTopics = '';
if ($xmlTopics && ($sxTopics = simplexml_load_file($xmlTopics))) {
$cssTopics = (string) ($sxTopics->display->css);
if ($xmlTopics && false !== $sxTopics = simplexml_load_file($xmlTopics)) {
$cssTopics = (string) $sxTopics->display->css;
}
$out .= '<style type="text/css">
@@ -96,7 +96,7 @@ class queries
$jsTopics = 'null';
$maxdepth = 0;
if (($sxTopics = simplexml_load_file($xmlTopics))) {
if (false !== $sxTopics = simplexml_load_file($xmlTopics)) {
$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']);
foreach ($fields as $name => $field) {
if ($sxe && $sxe->description && $sxe->description->$name) {
if (false !== $sxe && $sxe->description && $sxe->description->$name) {
$val = array();
foreach ($sxe->description->$name as $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)
{
declare(ticks = 1);
$this->dependencyContainer = $application;
$this->logger = $logger;
}
@@ -50,6 +51,14 @@ class task_Scheduler
* @throws Exception if scheduler is already running
* @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()
{
//prevent scheduler to fail if GV_cli is not provided
@@ -67,7 +76,10 @@ class task_Scheduler
if (\task_manager::isPosixPcntlSupported()) {
// 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;
}

View File

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

View File

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

View File

@@ -288,7 +288,7 @@ class task_period_archive extends task_abstract
$this->period = 60;
$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->period = (int) ($this->sxTaskSettings->period);
@@ -387,7 +387,7 @@ class task_period_archive extends task_abstract
$this->setLastExecTime();
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()));
} else {
// 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) {
// something happened : a least one file has moved
return self::STATE_MAXRECSDONE;
return 'MAXRECSDONE';
} elseif (memory_get_usage() >> 20 > 25) {
return self::STATE_MAXMEGSREACHED;
return 'MAXMEGSREACHED';
} else {
return 'NORECSTODO';
@@ -683,7 +683,7 @@ class task_period_archive extends task_abstract
try {
$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
if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') {
@@ -790,7 +790,7 @@ class task_period_archive extends task_abstract
$xp = new DOMXPath($dom);
if (($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) != false) {
if (false !== $sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml')) {
// test 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
// -- don't do, done in phase4
$sxGrouping = simplexml_load_file($groupingFile);
$sxGrouping = @simplexml_load_file($groupingFile);
$grp_rid = $sxGrouping['grouping'];
$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)) {
$caption = $this->readXMLForDatabox($metadatasStructure, $captionFile);
$captionStatus = $this->parseStatusBit(simplexml_load_file($captionFile));
$captionStatus = $this->parseStatusBit(@simplexml_load_file($captionFile));
if ($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)) {
$caption = $this->readXMLForDatabox($metadatasStructure, $captionFile);
$captionStatus = $this->parseStatusBit(simplexml_load_file($captionFile));
$captionStatus = $this->parseStatusBit(@simplexml_load_file($captionFile));
if ($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));
}
$sxcaption = @simplexml_load_file($pathfile);
if ( ! $sxcaption) {
if (false === $sxcaption = @simplexml_load_file($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
* @return string
*/
protected function parseStatusBit(\SimpleXMLElement $sxcaption)
protected function parseStatusBit($sxcaption)
{
$statBit = null;
if ('' !== $inStatus = (string) $sxcaption->status) {
$statBit = $inStatus;
if (!$sxcaption instanceof SimpleXMLElement) {
return null;
}
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)
{
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">
<?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)
{
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here...
// ... but we could check for safe values (ex. 0 < period < 3600)
if (false !== $sxml = simplexml_load_string($xml)) {
?>
<script type="text/javascript">
<?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)
{
if (($sxml = simplexml_load_string($xml)) != FALSE) { // in fact XML IS always valid here...
// ... but we could check for safe values
if (false !== $sxml = simplexml_load_string($xml)) {
if ((int) ($sxml->period) < 10) {
$sxml->period = 10;
} elseif ((int) ($sxml->period) > 1440) { // 1 jour
@@ -489,7 +488,7 @@ class task_period_outofdate extends task_abstract
$ret = self::STATUS_STOPPED;
$this->running = false;
} else {
if (($this->sxTaskSettings = simplexml_load_string($row['settings'])) != FALSE) {
if (false !== $this->sxTaskSettings = simplexml_load_string($row['settings'])) {
$period = (int) ($this->sxTaskSettings->period);
if ($period <= 0 || $period >= 24 * 60) {
$period = 60;

View File

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

View File

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

View File

@@ -83,7 +83,6 @@
{# SCRIPT - HORIZONTAL TABS #}
<script type ="text/javascript">
$(function() {
var pub_tabs = $("#pub_tabs");
var container = $('#dialog_publicator');
@@ -143,6 +142,45 @@ $(function() {
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(){
var $form = $(this).closest('form');
var method = $form.attr('method');
@@ -362,13 +400,13 @@ $(function() {
});
{% 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');
{% 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');
{% 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 %}
});
</script>

View File

@@ -237,15 +237,6 @@
{% endif %}
</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>
{% endif %}
</div>

View File

@@ -1,4 +1,3 @@
function thesau_show()
{
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 };
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:Remplacement du candidat "%s" :' %}', term) ;
msg += "<br/><br/>";
msg += $.sprintf('{% trans 'prod::thesaurusTab:dlg:Remplacer par "%s"' %}', f) ;
{% set message %}
{% trans 'prod::thesaurusTab:dlg:Remplacement du candidat "%(from)s" par "%(to)s"' %}
{% endset %}
$("#THPD_confirm_replace_dlg_msg").html(msg);
$("#THPD_confirm_replace_dlg").dialog('open');
var msg = $.sprintf("{{ message | e('js') }}", {'from':term, 'to':f});
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')
@@ -213,27 +221,23 @@ function T_filter_delayed2(f, delay, mode)
// ======================================================================================================
function T_replaceCandidates_OK(dlgnode)
function T_replaceCandidates_OK()
{
$("#THPD_confirm_replace_dlg_msg").html("{% trans 'prod::thesaurusTab:dlg:Remplacement en cours.' %}");
// 3 cases
// 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
{% set replaceing_msg %}
{% trans 'prod::thesaurusTab:dlg:Remplacement en cours.' %}
{% endset %}
var replacingBox = p4.Dialog.Create({
size : 'Alert'
});
replacingBox.setContent("{{ replaceing_msg | e('js') }}");
var parms = {
url: "/xmlhttp/replacecandidate.j.php",
data: {
"sbid" : trees.C._toReplace.sbas
, "cid" : trees.C._toReplace.cid
"id[]" : trees.C._toReplace.sbas + "." + trees.C._toReplace.cid
, "t" : trees.C._toReplace.replaceby
// , "debug" : '1'
, "debug" : '0'
},
async: false,
cache: false,
@@ -243,7 +247,25 @@ function T_replaceCandidates_OK(dlgnode)
{
trees.C._toReplace = null;
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
};
@@ -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 dst = trees.C._toAccept.dst.split('.');
@@ -272,12 +301,11 @@ function T_acceptCandidates_OK(dlgnode)
same_sbas = false;
t_ids.push(x.join('.'));
}
);
);
if(!same_sbas)
return;
var parms = {
url: "/xmlhttp/acceptcandidates.j.php",
data: {
@@ -313,17 +341,15 @@ function T_acceptCandidates_OK(dlgnode)
+ j.parm['id'].replace(new RegExp("\\.", "g"), "\\."); // escape les '.' pour jquery
$(z).replaceWith(j.html);
trees.C._toAccept = null;
thesauShowWizard("wiz_0",false);
$(dlgnode).dialog("close");
}
, "json");
}
// $("#THPD_confirm_accept_dlg_msg").dialog("close");
trees.C._toAccept = null;
thesauShowWizard("wiz_0",false);
acceptingBox.Close();
},
error:function(){},
timeout:function(){},
error:function(){acceptingBox.Close();},
timeout:function(){acceptingBox.Close();},
_ret: null // private alchemy
};
@@ -333,7 +359,14 @@ function T_acceptCandidates_OK(dlgnode)
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 lisel = trees.C.tree.find("LI .selected");
@@ -344,9 +377,9 @@ function C_deleteCandidates_OK()
x.shift();
t_ids.push(x.join('.'));
}
);
);
var parms = {
url:"/xmlhttp/deletecandidates.j.php",
url:"/xmlhttp/replacecandidate.j.php",
data:{"id[]":t_ids},
async:false,
cache:false,
@@ -354,12 +387,23 @@ function C_deleteCandidates_OK()
timeout:10*60*1000, // 10 minutes !
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();
}
$("#THPD_confirm_del_dlg").dialog("close");
},
_ret: null
};
@@ -379,23 +423,41 @@ function T_acceptCandidates(menuItem, menu, type)
if(lisel.length == 0)
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;
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
{
var term = lisel.eq(0).find("span span").html();
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:accepter le terme candidat "%s" ?' %}', term);
msg = $.sprintf("{{ messageMany | e('js') }}", lisel.length);
}
trees.C._toAccept.type = type;
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...
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
{
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
@@ -479,14 +549,22 @@ function C_MenuOption(menuItem, menu, option, parm)
case 'REPLACE':
// display helpful message into the thesaurus box...
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
{
var term = trees.C._selInfos.sel.eq(0).find("span span").html();
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:remplacer le terme "%s" des fiches par :' %}', term);
msg = $.sprintf('{{ messageMany |e }}', trees.C._selInfos.n);
}
p4.thesau.tabs.tabs('select', 0);
@@ -501,27 +579,43 @@ function C_MenuOption(menuItem, menu, option, parm)
case 'DELETE':
$("#THPD_WIZARDS DIV", p4.thesau.tabs).hide();
// display helpful message into the thesaurus box...
{% 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)
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
{
var term = trees.C._selInfos.sel.eq(0).find("span span").html();
msg = $.sprintf('{% trans 'prod::thesaurusTab:dlg:supprimer le terme "%s" des fiches ?' %}', term);
msg = $.sprintf("{{ messageMany | e('js') }}", trees.C._selInfos.n);
}
$("#THPD_confirm_del_dlg_msg").html(msg);
$("#THPD_confirm_del_dlg").dialog('open');
var confirmBox = p4.Dialog.Create({
size : 'Alert',
closeOnEscape : true,
cancelButton: true,
buttons: {
"Ok" : function() {
confirmBox.Close();
C_deleteCandidates_OK();
}
}
});
confirmBox.setContent(msg);
break;
}
}
function Xclick(e)
{
var x = e.srcElement ? e.srcElement : e.target;
@@ -662,15 +756,17 @@ function CXdblClick(e)
{
case "SPAN": // term
var li = $(x).closest('li');
var field = li.closest('[field]').attr('field');
if(typeof(field) != "undefined")
{
var tid = li.attr('id');
if(tid.substr(0,5)=="CX_P.")
{
var sbid = tid.split(".")[1];
var term = $(x).text();
var field = li.closest('[field]').attr('field');
doThesSearch('C', sbid, term, field);
}
}
break;
default:
break;
@@ -718,12 +814,6 @@ function doThesSearch(type, sbid, term, field)
}
function thesau_clickThesaurus(event) // onclick dans le thesaurus
{
// on cherche ou on a clique
@@ -828,7 +918,7 @@ function replaceEditSel(value)
{
if(!p4.thesau.lastTextfocus || !p4.thesau.lastTextfocus.selectedTerm)
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);
if(typeof(document.selection) != 'undefined')
{
@@ -1113,10 +1203,6 @@ function startThesaurus(){
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.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(
[
{
@@ -1290,7 +1319,7 @@ function startThesaurus(){
{% endfor %}
{
label:'{% trans 'prod::thesaurusTab:cmenu:Remplacer par...' %}',
disabled:true,
// disabled:true,
onclick:function(menuItem, menu)
{
C_MenuOption(menuItem, menu, 'REPLACE', null);
@@ -1298,7 +1327,7 @@ function startThesaurus(){
},
{
label:'{% trans 'boutton::supprimer' %}',
disabled:true,
// disabled:true,
onclick:function(menuItem, menu)
{
C_MenuOption(menuItem, menu, 'DELETE', null);
@@ -1341,6 +1370,16 @@ function startThesaurus(){
// glue selection info to the tree
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
{

View File

@@ -388,4 +388,23 @@ class BridgeApplication extends PhraseanetWebTestCaseAuthenticatedAbstract
$response = self::$DI['client']->getResponse();
$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();
$parm = $request->get_parms(
'sbid'
, 'cid' // candidate (id) to replace
, 't' // replacing term
, 'debug'
'id',
't',
'debug'
);
phrasea::headers(200, true, 'application/json', 'UTF-8', false);
if ($parm['debug'])
print("<pre>");
define('SEARCH_REPLACE_MAXREC', 25);
$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']);
$domth = $databox->get_dom_thesaurus();
$domct = $databox->get_dom_cterms();
foreach ($parm['id'] as $id) {
$id = explode('.', $id);
$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) {
$xpathct = new DOMXPath($domct);
if ($parm['debug']) {
var_dump($tsbas);
}
$field = null;
$x = null;
$appbox = $app['phraseanet.appbox'];
$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);
if ($nodes->length == 1) {
$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';
$lid .= ( $lid ? ',' : '') . "'" . $syid . "'";
$field = $sy->parentNode->parentNode->getAttribute('field');
if ( ! array_key_exists($field, $tsbas[$ksbas]['tvals'])) {
$tsbas[$ksbas]['tvals'][$field] = array();
}
$tsbas[$ksbas]['tvals'][$field][] = $sy;
}
}
if ($lid == '') {
// no cterm was found
continue;
}
$tsbas[$ksbas]['lid'] = $lid;
// 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']);
}
if ($parm['debug']) {
printf("(%d) nRecsToUpdate = %d \ntsbas: \n", __LINE__, $ret['nRecsToUpdate']);
print_r($tsbas);
}
if($ret['nRecsToUpdate'] <= SEARCH_REPLACE_MAXREC)
{
$unicode = new unicode;
foreach ($tsbas as $sbas) {
/* @var $databox databox */
try {
$databox = $appbox->get_databox($sbas['sbas_id']);
$connbas = $databox->get_connection();
} catch (Exception $e) {
continue;
}
// fix caption of records
foreach ($sbas['trids'] as $rid) {
if ($parm['debug']) {
printf("(%d) ======== working on record_id = %d ======= \n", __LINE__, $rid);
}
try {
$record = $databox->get_record($rid);
$metadatask = array(); // datas to keep
$metadatasd = array(); // datas to delete
/* @var $field caption_field */
foreach ($record->get_caption()->get_fields(null, true) as $field) {
$meta_struct_id = $field->get_meta_struct_id();
if ($parm['debug']) {
printf("(%d) field '%s' meta_struct_id=%s \n", __LINE__, $field->get_name(), $meta_struct_id);
}
/* @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("(%d) metadatask: \n", __LINE__);
var_dump($metadatask);
printf("(%d) metadatasd: \n", __LINE__);
var_dump($metadatasd);
}
if(count($metadatasd) > 0) {
if ( ! $parm['debug']) {
$record->set_metadatas($metadatasd, true);
$ret['nRecsUpdated']++;
}
}
} catch (\Exception $e) {
continue;
}
}
// delete the branch from the cterms
if ($parm['debug']) {
printf("cterms before :\n%s \n", $sbas['domct']->saveXML());
}
foreach($sbas['tvals'] as $tval) {
foreach($tval as $sy) {
// remove candidate from cterms
$te = $sy->parentNode;
$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'];
$ret['ctermsDeleted'][] = $sbas['sbas_id'] . '.' . $te->getAttribute('id');
}
if ($parm['debug'])
printf("%s : %s \n", __LINE__, var_export($t_rid, true));
$replacing = array();
$parm['t'] = explode(';', $parm['t']);
foreach ($parm['t'] as $t)
$replacing[] = simplified($t);
if ($parm['debug'])
printf("%s : replacing=%s \n", __LINE__, var_export($replacing, true));
foreach ($t_rid as $rid => $xml) {
if ($parm['debug'])
printf("%s rid=%s \n", __LINE__, $rid);
$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;
$nodetoreplace = null;
$nodestodelete = array();
$xp = new DOMXPath($dom);
$x = '/record/description/' . $field;
if ($parm['debug'])
printf("%s x=%s \n", __LINE__, $x);
$nodes = $xp->query($x);
$insertBefore = null;
if ($nodes->length <= 0)
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();
foreach ($nodes as $n) {
$value = simplified($n->textContent);
if (in_array($value['a'], $t_mval)) // a chance to delete doubles
continue;
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) {
unset($t_mval[$k]);
if ($parm['debug'])
printf("%s : after unset %s from t_mval %s \n", __LINE__, $k, var_export($t_mval, true));
foreach ($replacing as $r) {
if (in_array($r['a'], $t_mval))
continue;
for ($i = 0; $i < 9999 && array_key_exists($r['u'] . '_' . $i, $t_mval); $i ++ )
;
$t_mval[$r['u'] . '_' . $i] = $r['a'];
if ($parm['debug']) {
printf("cterms after :\n%s \n", $sbas['domct']->saveXML());
}
if ($parm['debug'])
printf("%s : after replace to t_mval %s \n", __LINE__, var_export($t_mval, true));
}
foreach ($nodestodelete as $n)
$n->parentNode->removeChild($n);
ksort($t_mval, SORT_STRING);
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 ($parm['debug'])
printf("%s : t_mval APRES = %s \n", __LINE__, var_export($t_mval, true));
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();
$databox->saveCterms($sbas['domct']);
}
$result['n_recsChanged'] ++;
}
}
}
} catch (Exception $e) {
}
$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);
}
function simplified($t)
{
$t = splitTermAndContext($t);
$unicode = new unicode();
$su = $unicode->remove_indexer_chars($sa = $t[0]);
if ($t[1]) {
$sa .= ' (' . ($t[1]) . ')';
$su .= ' (' . $unicode->remove_indexer_chars($t[1]) . ')';
}
return(array('a' => $sa, 'u' => $su));
}
print(p4string::jsonencode(array('parm' => $parm, 'result' => $result)));
if ($parm['debug'])
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));
}
/**
* @todo respecter les droits d'editing par collections
*/
print(p4string::jsonencode($ret));