5 * (c) Fil, toggg 2006-2013
9 if (!defined("_ECRIRE_INC_VERSION")) return;
11 define('_PREG_CRAYON', ',crayon\b[^<>\'"]+?\b((\w+)-(\w+)-(\w+(?:-\w+)*))\b,');
13 // Compatibilite pour 1.92 : on a besoin de sql_fetch et table_objet_sql
14 if ($GLOBALS['spip_version_code'] < '1.93' AND $f = charger_fonction('compat_crayons', 'inc'))
17 // Autoriser les crayons sur les tables non SPIP ?
18 // Par defaut : oui (pour les admins complets, si autoriser_defaut_dist()) ;
19 // mettre a false en cas de mutualisation par prefixe de table,
20 // sinon on ne peut pas garantir que les sites sont hermetiques
21 if(!defined('_CRAYONS_TABLES_EXTERNES'))
22 define('_CRAYONS_TABLES_EXTERNES', true);
24 // Autorisations non prevues par le core
25 include_spip('inc/autoriser');
27 include_spip('inc/crayons-json');
29 if (!function_exists('autoriser_meta_modifier_dist')) {
31 * Autorisation d'éditer les configurations dans spip_meta
33 * Les admins complets OK pour certains champs,
34 * Sinon, il faut être webmestre
37 * Attention sur les SPIP < 11515 (avant 04/2008) inc/autoriser
38 * passe seulement intval($id) alors qu'ici la cle est une chaine...
40 * @param string $faire Action demandée
41 * @param string $type Type d'objet sur lequel appliquer l'action
42 * @param int $id Identifiant de l'objet
43 * @param array $qui Description de l'auteur demandant l'autorisation
44 * @param array $opt Options de cette autorisation
45 * @return bool true s'il a le droit, false sinon
47 function autoriser_meta_modifier_dist($faire, $type, $id, $qui, $opt) {
48 // Certaines cles de configuration sont echapées ici (cf #EDIT_CONFIG{demo/truc})
49 // $id = str_replace('__', '/', $id);
50 if (in_array("$id", array(
51 'nom_site', 'slogan_site', 'descriptif_site', 'email_webmaster'
53 return autoriser('configurer', null, null, $qui);
55 return autoriser('webmestre', null, null, $qui);
59 // table spip_messages, la c'est tout simplement non (peut mieux faire,
60 // mais c'est a voir dans le core/organiseur ou dans autorite)
61 if (defined('_DIR_PLUGIN_ORGANISEUR'))
62 include_spip('organiseur_autoriser');
63 if (!function_exists('autoriser_message_modifier_dist')) {
64 function autoriser_message_modifier_dist($faire, $type, $id, $qui, $opt) {
68 //compat 192 documents
69 if ($GLOBALS['spip_version_code'] < '1.93'){
70 if (!function_exists('get_spip_doc')){
71 function get_spip_doc($fichier) {
73 if (preg_match(',^\w+://,', $fichier))
76 // gestion d'erreurs, fichier=''
77 if (!strlen($fichier))
81 return (strpos($fichier, _DIR_IMG
) === false)
88 // Autoriser l'usage des crayons ?
89 function autoriser_crayonner_dist($faire, $type, $id, $qui, $opt) {
90 // Le type pouvant etre une table, verifier les autoriser('modifier')
91 // correspondant ; ils demandent le nom de l'objet: spip_articles => article
92 // ex: spip_articles => 'article'
93 $type = preg_replace(',^spip_(.*?)s?$,', '\1', $type);
94 if (strlen($GLOBALS['table_prefix']))
95 $type = preg_replace(',^'.$GLOBALS['table_prefix'].'_(.*?)s?$,', '\1', $type);
97 // Tables non SPIP ? Si elles sont interdites il faut regarder
98 // quelle table on appelle, et verifier si elle est "interne"
99 if (!_CRAYONS_TABLES_EXTERNES
) {
100 include_spip('base/serial');
101 include_spip('base/auxiliaires');
102 include_spip('public/parametrer');
103 if (!isset($GLOBALS['tables_principales']['spip_'.table_objet($type)])
104 AND !isset($GLOBALS['tables_auxiliaires']['spip_'.table_objet($type)]))
108 // Traduire le modele en liste de champs
109 if (isset($opt['modele']))
110 $opt['champ'] = $opt['modele'];
112 // Pour un auteur, si le champ est statut ou email, signaler l'option
113 // ad hoc (cf. inc/autoriser)
114 if ($type == 'auteur'
115 AND in_array($opt['champ'], array('statut', 'email')))
116 $opt[$opt['champ']] = true;
119 autoriser('modifier', $type, $id, $qui, $opt)
123 // Si un logo est demande, on renvoie la date dudit logo (permettra de gerer
124 // un "modifie par ailleurs" si la date a change, rien de plus)
125 function valeur_champ_logo($table, $id, $champ) {
126 $chercher_logo = charger_fonction('chercher_logo', 'inc');
127 $on = $chercher_logo($id, id_table_objet($table), 'on');
128 return $on ?
filemtime($on[0]) : false;
131 // Idem : si un doc est demande, on renvoie la date du doc
132 function valeur_champ_document($table, $id, $champ) {
133 $s = spip_query("SELECT date FROM spip_documents WHERE id_document="._q($id));
134 if ($t = sql_fetch($s))
138 function valeur_champ_vignette($table, $id, $champ) {
139 $vignette = sql_getfetsel('id_vignette','spip_documents','id_document='.intval($id));
140 if(is_numeric($vignette) && ($vignette > 0)){
141 $date = sql_getfetsel('date','spip_documents','id_document='.intval($vignette));
143 return $date ?
$date : false;
145 // cette fonction de revision recoit le fichier upload a passer en logo
146 // en reference : le nom du widget, pour aller chercher d'autres donnees
148 function logo_revision($id, $file, $type, $ref) {
149 $chercher_logo = charger_fonction('chercher_logo', 'inc');
150 $_id_objet = id_table_objet($type);
152 // Chargement d'un nouveau logo ?
154 define('FILE_UPLOAD', true); // message pour crayons_json_export :(
156 // supprimer l'ancien logo
157 $on = $chercher_logo($id, $_id_objet, 'on');
158 if ($on) @unlink
($on[0]);
160 // ajouter le nouveau
161 include_spip('action/iconifier');
162 action_spip_image_ajouter_dist(
163 type_du_logo($_id_objet).'on'.$id, false, false
169 // Suppression du logo ?
170 if ($wid = array_pop($ref)
171 AND $_POST['content_'.$wid.'_logo_supprimer'] == 'on') {
172 if ($on = $chercher_logo($id, $_id_objet, 'on'))
177 if (is_array($cfg = @unserialize
($GLOBALS['meta']['crayons']))
178 AND $max = intval($cfg['reduire_logo'])) {
179 $on = $chercher_logo($id, $_id_objet, 'on');
180 include_spip('inc/filtres');
181 @copy
($on[0], $temp = _DIR_VAR
.'tmp'.rand(0,999).'.'.$on[3]);
182 $img1 = filtrer('image_reduire', $temp, $max);
183 $img2 = preg_replace(',[?].*,', '', extraire_attribut($img1, 'src'));
184 if (@file_exists
($img2)
185 AND $img2 != $temp) {
187 $dest = $on[1].$on[2].'.'
188 .preg_replace(',^.*\.(gif|jpg|png)$,', '\1', $img2);
189 @rename
($img2,$dest);
198 // cette fonction de revision recoit le fichier upload a passer en document
199 function document_fichier_revision($id, $data, $type, $ref) {
201 $s = spip_query("SELECT * FROM spip_documents WHERE id_document=".intval($id));
202 if (!$t = sql_fetch($s))
206 // Envoi d'une URL de document distant ?
207 // TODO: verifier l'extension distante, sinon tout explose
209 AND preg_match(',^(https?|ftp)://.+,', $data['fichier'])) {
210 include_spip('inc/modifier');
211 modifier_contenu('document', $id,
212 array('champs' => array('fichier', 'distant')),
213 array('fichier' => $data['fichier'], 'distant' => 'oui')
220 // Chargement d'un nouveau doc ?
221 if ($data['document']) {
223 $arg = $data['document'];
226 * Méthode >= SPIP 3.0
227 * ou SPIP 2.x + Mediathèque
229 if($ajouter_documents = charger_fonction('ajouter_documents','action',true)){
230 $actifs = $ajouter_documents($id,array($arg),'', 0,$t['mode']);
240 else if($ajouter_documents = charger_fonction('ajouter_documents','inc',true)){
241 check_upload_error($arg['error']);
242 $x = $ajouter_documents($arg['tmp_name'], $arg['name'],
243 'article', 0, 'document', null, $actifs);
244 // $actifs contient l'id_document nouvellement cree
245 // on recopie les donnees interessantes dans l'ancien
246 $extension=", extension ";
248 if ($GLOBALS['spip_version_code'] < '1.93')
251 if ($id_new = array_pop($actifs)
252 AND $s = spip_query("SELECT fichier, taille, largeur, hauteur $extension, distant FROM spip_documents
253 WHERE id_document="._q($id_new))
254 AND $new = sql_fetch($s)) {
255 define('FILE_UPLOAD', true); // message pour crayons_json_export :(
257 // Une vignette doit rester une image
258 if ($t['mode'] == 'vignette'
259 AND !in_array($new['extension'], array('jpg', 'gif', 'png')))
262 // Maintenant on est bon, on recopie les nouvelles donnees
263 // dans l'ancienne ligne spip_documents
264 include_spip('inc/modifier');
265 modifier_contenu('document', $id,
266 # 'champs' inutile a partir de SPIP 11348
267 array('champs' => array_keys($new)),
270 // supprimer l'ancien document (sauf s'il etait distant)
271 if ($t['distant'] != 'oui'
272 AND file_exists(get_spip_doc($t['fichier'])))
273 supprimer_fichier(get_spip_doc($t['fichier']));
275 // Effacer la ligne temporaire de spip_document
276 spip_query("DELETE FROM spip_documents WHERE id_document="._q($id_new));
278 // oublier id_document temporaire (ca marche chez moi, sinon bof)
279 spip_query("ALTER TABLE spip_documents AUTO_INCREMENT="._q($id_new));
287 // cette fonction de revision soit supprime la vignette d'un document,
288 // soit recoit le fichier upload a passer ou remplacer la vignette du document
289 function vignette_revision($id, $data, $type, $ref) {
290 $s = sql_fetsel("id_document,id_vignette","spip_documents","id_document=".intval($id));
294 include_spip('inc/modifier');
295 include_spip('inc/documents');
296 include_spip('action/editer_document');//pour revision_document
297 // Chargement d'un nouveau doc ?
298 if ($data['vignette']) {
299 define('FILE_UPLOAD', true);
300 if(is_numeric($s['id_vignette']) && ($s['id_vignette']>0)){
301 spip_log('suppression de la vignette');
302 // Suppression du document
303 $vignette = sql_getfetsel('fichier', 'spip_documents', 'id_document='.intval($s['id_vignette']));
304 if (@file_exists
($f = get_spip_doc($vignette))) {
305 spip_log("efface $f");
306 supprimer_fichier($f);
308 sql_delete('spip_documents', 'id_document='.intval($s['id_vignette']));
309 sql_delete('spip_documents_liens', 'id_document='.intval($s['id_vignette']));
311 pipeline('post_edition',
314 'operation' => 'supprimer_document',
315 'table' => 'spip_documents',
316 'id_objet' => $s['id_vignette']
324 $arg = $data['vignette'];
325 check_upload_error($arg['error']);
326 // Ajout du document comme vignette
329 * Méthode >= SPIP 3.0
330 * ou SPIP 2.x + Mediatheque
332 if($ajouter_documents = charger_fonction('ajouter_documents','action',true)){
333 $x = $ajouter_documents(null,array($arg),'', 0, 'vignette');
334 $vignette = reset($x);
335 if(intval($vignette))
336 document_modifier($id, array('id_vignette'=>$vignette));
337 else if($id_vignette)
338 document_modifier($id, array('id_vignette'=>$id_vignette));
343 else if($ajouter_documents = charger_fonction('ajouter_documents','inc',true)){
344 // On remet l'id_vignette a 0 si on l'a supprimé
345 if($id_vignette) revision_document($s['id_document'], array('id_vignette'=>0));
346 $x = $ajouter_documents($arg['tmp_name'], $arg['name'],'','', 'vignette', $id, $actifs);
350 // Suppression de la vignette ?
351 if ($wid = array_pop($ref)
352 AND $_POST['content_'.$wid.'_vignette_supprimer'] == 'on') {
353 if(is_numeric($s['id_vignette']) && ($s['id_vignette']>0)){
354 // Suppression du document
355 $vignette = sql_getfetsel('fichier', 'spip_documents', 'id_document='.intval($s['id_vignette']));
356 if (@file_exists
($f = get_spip_doc($vignette))) {
357 spip_log("efface $f");
358 supprimer_fichier($f);
360 sql_delete('spip_documents', 'id_document='.intval($s['id_vignette']));
361 sql_delete('spip_documents_liens', 'id_document='.intval($s['id_vignette']));
363 pipeline('post_edition',
366 'operation' => 'supprimer_document',
367 'table' => 'spip_documents',
368 'id_objet' => $s['id_vignette']
374 // On remet l'id_vignette a 0
375 revision_document($s['id_document'], array('id_vignette'=>0));
382 function colonne_table($type, $col) {
383 list($distant,$table) = distant_table($type);
385 if (!(($tabref = &crayons_get_table($table, $nom_table))
386 && isset($tabref['field'][$col])
387 && ($brut = $tabref['field'][$col]))) {
390 $ana = explode(' ', $brut);
393 $ret = array('brut' => $brut,
394 'type' => '', 'notnull' => false, 'long' => 0, 'def' => '');
395 foreach ($ana as $mot) {
397 case 0: $ret['type'] = ($mot = strtolower($mot));
398 case 1: if ($mot[strlen($mot) - 1] == ')') {
399 $pos = strpos($mot, '(');
400 $ret['type'] = strtolower(substr($mot, 0, $pos++
));
401 $vir = explode(',', substr($mot, $pos, -1));
402 if ($ret['type'] == 'enum') {
404 } elseif (count($vir) > 1) {
407 $ret['long'] = $vir[0];
416 case 2: switch (strtolower($mot)) {
425 case 3: $ret['notnull'] = strtolower($mot) == 'null';
428 case 4: $df1 = strpos('"\'', $mot[0]) !== false?
$mot[0] : '';
430 case 5: $ret['def'] .= $sep . $mot;
435 if ($df1 == $mot[strlen($mot) - 1]) {
436 $ret['def'] = substr($ret['def'], 1, -1);
448 * Obtient le nom de la table ainsi que sa ou ses clés primaires
450 * @param string $type
451 * Table sur laquelle s'applique le crayon.
452 * Ce type peut contenir le nom d'un connecteur distant tel que `{connect}__{table}`
455 * - false si on ne trouve pas de table ou de table ayant de clé primaire
457 * - - nom de la table sql
458 * - - tableau des noms de clés primaires
460 function crayons_get_table_name_and_primary($type) {
461 static $types = array();
462 if (isset($types[$type])) {
463 return $types[$type];
467 if ($tabref = &crayons_get_table($type, $nom_table)
468 and ($tabid = explode(',', $tabref['key']['PRIMARY KEY'])))
470 return $types[$type] = array($nom_table, $tabid);
472 spip_log('crayons: table ' . $type . ' inconnue');
473 return $types[$type] = false;
477 function table_where($type, $id, $where_en_tableau = false) {
480 if (!$infos = crayons_get_table_name_and_primary($type)) {
481 return array(false, false);
484 list($nom_table, $tabid) = $infos;
488 $id = explode('-', $id);
489 // sortie tableau pour sql_updateq
490 if ($where_en_tableau) {
492 foreach ($id as $idcol => $idval) {
493 $where[] = '`' . (is_int($idcol) ?
trim($tabid[$idcol]) : $idcol) . '`=' . sql_quote($idval);
495 // sinon sortie texte pour sql_query
499 foreach ($id as $idcol => $idval) {
500 $where .= $and . '`' . (is_int($idcol) ?
trim($tabid[$idcol]) : $idcol) . '`=' . _q($idval);
504 return array($nom_table, $where);
506 // var_dump(colonne_table('forum', 'id_syndic')); die();
508 function valeur_colonne_table_dist($type, $col, $id) {
510 // Table introuvable ou sans clé primaire
511 if (!$infos = crayons_get_table_name_and_primary($type)) {
514 $table = reset($infos);
519 foreach ($col as $champ) {
520 if (function_exists($f = 'valeur_champ_'.$table.'_'.$champ) OR function_exists($f = 'valeur_champ_'.$champ)) {
521 $r[$champ] = $f($table, $id, $champ);
522 $col = array_diff($col, array($champ));
528 list($distant, $table) = distant_table($type);
529 list($nom_table, $where) = table_where($type, $id);
532 'SELECT `' . implode($col, '`, `') .
533 '` FROM ' . $nom_table . ' WHERE ' . $where, $distant)
534 AND $t = sql_fetch($s)){
535 $r = array_merge($r, $t);
543 * Extrait la valeur d'une ou plusieurs colonnes d'une table
545 * @param string $table
546 * Type d'objet de la table (article)
547 * @param string|array $col
548 * Nom de la ou des colonnes (ps)
550 * Identifiant de l'objet
552 * Couples Nom de la colonne => Contenu de la colonne
554 function valeur_colonne_table($table, $col, $id) {
558 if (function_exists($f = $table.'_valeur_colonne_table_dist')
559 OR function_exists($f = $table.'_valeur_colonne_table')
560 OR $f = 'valeur_colonne_table_dist')
561 return $f($table, $col, $id);
565 * Extrait la valeur d'une configuration en meta
567 * Pour ces données, il n'y a toujours qu'une colonne (valeur),
568 * mais on gère l'enregistrement et la lecture via lire_config ou ecrire_config
569 * dès que l'on demande des sous parties d'une configuration.
571 * On ne retourne alors ici dans 'valeur' que la sous-partie demandée si
574 * @param string $table
575 * Nom de la table (meta)
577 * Nom des colonnes (valeur)
579 * Nom ou clé de configuration (descriptif_site ou demo__truc pour demo/truc)
581 * Couple valeur => Contenu de la configuration
583 function meta_valeur_colonne_table_dist($table, $col, $id) {
584 // Certaines clés de configuration sont echapées ici (cf #EDIT_CONFIG{demo/truc})
585 $id = str_replace('__', '/', $id);
587 // Éviter de planter les vieux SPIP
588 if (false === strpos($id, '/')) {
589 $config = isset($GLOBALS['meta'][$id]) ?
$GLOBALS['meta'][$id] : '';
590 // SPIP 3 ou Bonux 2 ou CFG
592 include_spip('inc/config');
593 $config = lire_config($id, '');
595 return array('valeur' => $config);
599 function return_log($var) {
600 die(crayons_json_export(array('$erreur'=> var_export($var,true))));
603 function _U($texte, $params=array()) {
604 include_spip('inc/charsets');
605 return unicode2charset(html2unicode(_T($texte, $params)));
609 * Obtenir la configuration des crayons
611 * @note wdgcfg = widget config :-)
614 * Couples : attribut => valeur
617 $php = function_exists('crayons_config') ?
crayons_config() : array();
618 include_spip('inc/meta');
621 $metacrayons = empty($meta['crayons']) ?
array() : unserialize($meta['crayons']);
624 'msgNoChange' => false,
625 'msgAbandon' => false, /* etait: true */
627 'yellow_fade' => false,
628 'clickhide' => false /* etait: true */
631 $wdgcfg[$cfgi] = isset($php[$cfgi]) ?
$php[$cfgi] :
632 isset($metacrayons[$cfgi]) ?
$metacrayons[$cfgi] : $def;
637 function &crayons_get_table($type, &$nom_table) {
638 list($distant,$table) = distant_table($type);
639 static $return = array();
640 static $noms = array();
641 if (!isset($return[$table])) {
642 $try = array(table_objet_sql($table), 'spip_'.table_objet($table), 'spip_' . $table . 's', $table . 's', 'spip_' . $table, $table);
644 // premiere possibilite (à partir de 1.9.3) : regarder directement la base
645 if (function_exists('sql_showtable')) {
646 foreach ($try as $nom) {
647 if ($q = sql_showtable($nom , !$distant , $distant)) {
648 $noms[$table] = $nom;
649 $return[$table] = $q;
655 // seconde, une heuristique 1.9.2
656 if (!isset($return[$table])) {
657 include_spip('base/serial');
658 include_spip('base/auxiliaires');
659 include_spip('public/parametrer');
660 foreach(array('tables_principales', 'tables_auxiliaires') as $categ) {
661 foreach ($try as $nom) {
662 if (isset($GLOBALS[$categ][$nom])) {
663 $noms[$table] = $nom;
664 $return[$table] = & $GLOBALS[$categ][$nom];
672 $nom_table = $noms[$table];
673 return $return[$table];
676 function distant_table($type) {
677 //separation $type en $distant $table
678 //separateur double underscore "__"
679 strstr($type,'__')?
list($distant,$table) = explode('__',$type) : list($distant,$table) = array(False,$type);
680 return array($distant,$table);