Skip to content
Extraits de code Groupes Projets
ordonner_liens_blocks.php 2,16 Kio
<?php

/**
 * Action ordonnant un lien sur une table de liens
 *
 * @plugin     Medias
 * @copyright  2017
 * @author     Matthieu Marcillaud
 * @licence    GNU/GPL
 * @package    SPIP\Ordoc\Action
 */

if (!defined('_ECRIRE_INC_VERSION')) {
	return;
}

/**
 * @throws \JsonException
 */
function action_ordonner_liens_blocks_dist() {
	include_spip('inc/autoriser');
	include_spip('base/objets');
	include_spip('action/editer_liens');

	// objet lié
	$objet_lie = objet_type((string)_request('objet_lie'));
	$id_objet_lie = (int)_request('id_objet_lie');

	// ordre des éléments
	$ordre = _request('ordre');

	if (!$objet_lie or !$id_objet_lie or !$ordre or !is_array($ordre)) {
		return envoyer_json_erreur(_T('medias:erreur_objet_absent') . ' ' . _T('medias:erreur_deplacement_impossible'));
	}

	if (!autoriser('modifier', $objet_lie, $id_objet_lie)) {
		return envoyer_json_erreur(_T('medias:erreur_autorisation') . ' ' . _T('medias:erreur_deplacement_impossible'));
	}

	$success = $errors = [];

	$actuels = sql_allfetsel(
		['id_block AS id', 'rang_lien'],
		'spip_blocks',
		[
			sql_in('id_block', $ordre),
			'objet = ' . sql_quote($objet_lie),
			'id_objet = ' . sql_quote($id_objet_lie),
		]
	);

	$futurs = array_flip($ordre);
	// ordre de 1 à n (pas de 0 à n).
	array_walk($futurs, function (&$v) {
		$v++;
	});

	$updates = [];

	foreach ($actuels as $l) {
		if ($futurs[$l['id']] !== $l['rang_lien']) {
			$updates[$l['id']] = $futurs[$l['id']];
		}
	}

	if ($updates) {
		foreach ($updates as $id => $ordre) {
			sql_updateq(
				'spip_blocks',
				['rang_lien' => (int)$ordre],
				[
					'id_block = ' . (int)$id,
					'objet = ' . sql_quote($objet_lie),
					'id_objet = ' . sql_quote($id_objet_lie),
				]
			);
		}
	}

	envoyer_json_envoi([
		'done'    => true,
		'success' => $success,
		'errors'  => $errors,
	]);
}

/**
 * @throws \JsonException
 */
function envoyer_json_envoi($data) {
	header('Content-Type: application/json; charset=' . $GLOBALS['meta']['charset']);
	echo json_encode($data, JSON_THROW_ON_ERROR);
}

/**
 * @throws \JsonException
 */
function envoyer_json_erreur($msg) {
	envoyer_json_envoi([
		'done'    => false,
		'success' => [],
		'errors'  => [$msg],
	]);
}