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 if (include_spip("action/editer_logo")
157 AND function_exists("logo_modifier")){
158 logo_modifier($type, $id, "on", $file['logo']);
162 // supprimer l'ancien logo
163 $on = $chercher_logo($id, $_id_objet, 'on');
164 if ($on) @unlink
($on[0]);
166 // ajouter le nouveau
167 include_spip('action/iconifier');
168 action_spip_image_ajouter_dist(
169 type_du_logo($_id_objet).'on'.$id, false, false
175 // Suppression du logo ?
176 if ($wid = array_pop($ref)
177 AND $_POST['content_'.$wid.'_logo_supprimer'] == 'on') {
178 if (include_spip("action/editer_logo")
179 AND function_exists("logo_supprimer")){
180 logo_supprimer($type, $id, "on");
183 if ($on = $chercher_logo($id, $_id_objet, 'on'))
190 if (is_array($cfg = @unserialize
($GLOBALS['meta']['crayons']))
191 AND $max = intval($cfg['reduire_logo'])) {
192 $on = $chercher_logo($id, $_id_objet, 'on');
193 include_spip('inc/filtres');
194 @copy
($on[0], $temp = _DIR_VAR
.'tmp'.rand(0,999).'.'.$on[3]);
195 $img1 = filtrer('image_reduire', $temp, $max);
196 $img2 = preg_replace(',[?].*,', '', extraire_attribut($img1, 'src'));
197 if (@file_exists
($img2)
198 AND $img2 != $temp) {
199 if (include_spip("action/editer_logo")
200 AND function_exists("logo_modifier")){
201 logo_modifier($type, $id, "on", $img2);
205 $dest = $on[1].$on[2].'.'
206 .preg_replace(',^.*\.(gif|jpg|png)$,', '\1', $img2);
207 @rename
($img2,$dest);
217 // cette fonction de revision recoit le fichier upload a passer en document
218 function document_fichier_revision($id, $data, $type, $ref) {
220 $s = spip_query("SELECT * FROM spip_documents WHERE id_document=".intval($id));
221 if (!$t = sql_fetch($s))
225 // Envoi d'une URL de document distant ?
226 // TODO: verifier l'extension distante, sinon tout explose
228 AND preg_match(',^(https?|ftp)://.+,', $data['fichier'])) {
229 include_spip('inc/modifier');
230 modifier_contenu('document', $id,
231 array('champs' => array('fichier', 'distant')),
232 array('fichier' => $data['fichier'], 'distant' => 'oui')
239 // Chargement d'un nouveau doc ?
240 if ($data['document']) {
242 $arg = $data['document'];
245 * Méthode >= SPIP 3.0
246 * ou SPIP 2.x + Mediathèque
248 if($ajouter_documents = charger_fonction('ajouter_documents','action',true)){
249 $actifs = $ajouter_documents($id,array($arg),'', 0,$t['mode']);
259 else if($ajouter_documents = charger_fonction('ajouter_documents','inc',true)){
260 check_upload_error($arg['error']);
261 $x = $ajouter_documents($arg['tmp_name'], $arg['name'],
262 'article', 0, 'document', null, $actifs);
263 // $actifs contient l'id_document nouvellement cree
264 // on recopie les donnees interessantes dans l'ancien
265 $extension=", extension ";
267 if ($GLOBALS['spip_version_code'] < '1.93')
270 if ($id_new = array_pop($actifs)
271 AND $s = spip_query("SELECT fichier, taille, largeur, hauteur $extension, distant FROM spip_documents
272 WHERE id_document="._q($id_new))
273 AND $new = sql_fetch($s)) {
274 define('FILE_UPLOAD', true); // message pour crayons_json_export :(
276 // Une vignette doit rester une image
277 if ($t['mode'] == 'vignette'
278 AND !in_array($new['extension'], array('jpg', 'gif', 'png')))
281 // Maintenant on est bon, on recopie les nouvelles donnees
282 // dans l'ancienne ligne spip_documents
283 include_spip('inc/modifier');
284 modifier_contenu('document', $id,
285 # 'champs' inutile a partir de SPIP 11348
286 array('champs' => array_keys($new)),
289 // supprimer l'ancien document (sauf s'il etait distant)
290 if ($t['distant'] != 'oui'
291 AND file_exists(get_spip_doc($t['fichier'])))
292 supprimer_fichier(get_spip_doc($t['fichier']));
294 // Effacer la ligne temporaire de spip_document
295 spip_query("DELETE FROM spip_documents WHERE id_document="._q($id_new));
297 // oublier id_document temporaire (ca marche chez moi, sinon bof)
298 spip_query("ALTER TABLE spip_documents AUTO_INCREMENT="._q($id_new));
306 // cette fonction de revision soit supprime la vignette d'un document,
307 // soit recoit le fichier upload a passer ou remplacer la vignette du document
308 function vignette_revision($id, $data, $type, $ref) {
309 $s = sql_fetsel("id_document,id_vignette","spip_documents","id_document=".intval($id));
313 include_spip('inc/modifier');
314 include_spip('inc/documents');
315 include_spip('action/editer_document');//pour revision_document
316 // Chargement d'un nouveau doc ?
317 if ($data['vignette']) {
318 define('FILE_UPLOAD', true);
319 if(is_numeric($s['id_vignette']) && ($s['id_vignette']>0)){
320 spip_log('suppression de la vignette');
321 // Suppression du document
322 $vignette = sql_getfetsel('fichier', 'spip_documents', 'id_document='.intval($s['id_vignette']));
323 if (@file_exists
($f = get_spip_doc($vignette))) {
324 spip_log("efface $f");
325 supprimer_fichier($f);
327 sql_delete('spip_documents', 'id_document='.intval($s['id_vignette']));
328 sql_delete('spip_documents_liens', 'id_document='.intval($s['id_vignette']));
330 pipeline('post_edition',
333 'operation' => 'supprimer_document',
334 'table' => 'spip_documents',
335 'id_objet' => $s['id_vignette']
343 $arg = $data['vignette'];
344 check_upload_error($arg['error']);
345 // Ajout du document comme vignette
348 * Méthode >= SPIP 3.0
349 * ou SPIP 2.x + Mediatheque
351 if($ajouter_documents = charger_fonction('ajouter_documents','action',true)){
352 $x = $ajouter_documents(null,array($arg),'', 0, 'vignette');
353 $vignette = reset($x);
354 if(intval($vignette))
355 document_modifier($id, array('id_vignette'=>$vignette));
356 else if($id_vignette)
357 document_modifier($id, array('id_vignette'=>$id_vignette));
362 else if($ajouter_documents = charger_fonction('ajouter_documents','inc',true)){
363 // On remet l'id_vignette a 0 si on l'a supprimé
364 if($id_vignette) revision_document($s['id_document'], array('id_vignette'=>0));
365 $x = $ajouter_documents($arg['tmp_name'], $arg['name'],'','', 'vignette', $id, $actifs);
369 // Suppression de la vignette ?
370 if ($wid = array_pop($ref)
371 AND $_POST['content_'.$wid.'_vignette_supprimer'] == 'on') {
372 if(is_numeric($s['id_vignette']) && ($s['id_vignette']>0)){
373 // Suppression du document
374 $vignette = sql_getfetsel('fichier', 'spip_documents', 'id_document='.intval($s['id_vignette']));
375 if (@file_exists
($f = get_spip_doc($vignette))) {
376 spip_log("efface $f");
377 supprimer_fichier($f);
379 sql_delete('spip_documents', 'id_document='.intval($s['id_vignette']));
380 sql_delete('spip_documents_liens', 'id_document='.intval($s['id_vignette']));
382 pipeline('post_edition',
385 'operation' => 'supprimer_document',
386 'table' => 'spip_documents',
387 'id_objet' => $s['id_vignette']
393 // On remet l'id_vignette a 0
394 revision_document($s['id_document'], array('id_vignette'=>0));
401 function colonne_table($type, $col) {
402 list($distant,$table) = distant_table($type);
404 if (!(($tabref = &crayons_get_table($table, $nom_table))
405 && isset($tabref['field'][$col])
406 && ($brut = $tabref['field'][$col]))) {
409 $ana = explode(' ', $brut);
412 $ret = array('brut' => $brut,
413 'type' => '', 'notnull' => false, 'long' => 0, 'def' => '');
414 foreach ($ana as $mot) {
416 case 0: $ret['type'] = ($mot = strtolower($mot));
417 case 1: if ($mot[strlen($mot) - 1] == ')') {
418 $pos = strpos($mot, '(');
419 $ret['type'] = strtolower(substr($mot, 0, $pos++
));
420 $vir = explode(',', substr($mot, $pos, -1));
421 if ($ret['type'] == 'enum') {
423 } elseif (count($vir) > 1) {
426 $ret['long'] = $vir[0];
435 case 2: switch (strtolower($mot)) {
444 case 3: $ret['notnull'] = strtolower($mot) == 'null';
447 case 4: $df1 = strpos('"\'', $mot[0]) !== false?
$mot[0] : '';
449 case 5: $ret['def'] .= $sep . $mot;
454 if ($df1 == $mot[strlen($mot) - 1]) {
455 $ret['def'] = substr($ret['def'], 1, -1);
467 * Obtient le nom de la table ainsi que sa ou ses clés primaires
469 * @param string $type
470 * Table sur laquelle s'applique le crayon.
471 * Ce type peut contenir le nom d'un connecteur distant tel que `{connect}__{table}`
474 * - false si on ne trouve pas de table ou de table ayant de clé primaire
476 * - - nom de la table sql
477 * - - tableau des noms de clés primaires
479 function crayons_get_table_name_and_primary($type) {
480 static $types = array();
481 if (isset($types[$type])) {
482 return $types[$type];
486 if ($tabref = &crayons_get_table($type, $nom_table)
487 and ($tabid = explode(',', $tabref['key']['PRIMARY KEY'])))
489 return $types[$type] = array($nom_table, $tabid);
491 spip_log('crayons: table ' . $type . ' inconnue');
492 return $types[$type] = false;
496 function table_where($type, $id, $where_en_tableau = false) {
499 if (!$infos = crayons_get_table_name_and_primary($type)) {
500 return array(false, false);
503 list($nom_table, $tabid) = $infos;
507 $id = explode('-', $id);
508 // sortie tableau pour sql_updateq
509 if ($where_en_tableau) {
511 foreach ($id as $idcol => $idval) {
512 $where[] = '`' . (is_int($idcol) ?
trim($tabid[$idcol]) : $idcol) . '`=' . sql_quote($idval);
514 // sinon sortie texte pour sql_query
518 foreach ($id as $idcol => $idval) {
519 $where .= $and . '`' . (is_int($idcol) ?
trim($tabid[$idcol]) : $idcol) . '`=' . _q($idval);
523 return array($nom_table, $where);
525 // var_dump(colonne_table('forum', 'id_syndic')); die();
527 function valeur_colonne_table_dist($type, $col, $id) {
529 // Table introuvable ou sans clé primaire
530 if (!$infos = crayons_get_table_name_and_primary($type)) {
533 $table = reset($infos);
538 foreach ($col as $champ) {
539 if (function_exists($f = 'valeur_champ_'.$table.'_'.$champ) OR function_exists($f = 'valeur_champ_'.$champ)) {
540 $r[$champ] = $f($table, $id, $champ);
541 $col = array_diff($col, array($champ));
547 list($distant, $table) = distant_table($type);
548 list($nom_table, $where) = table_where($type, $id);
551 'SELECT `' . implode($col, '`, `') .
552 '` FROM ' . $nom_table . ' WHERE ' . $where, $distant)
553 AND $t = sql_fetch($s)){
554 $r = array_merge($r, $t);
562 * Extrait la valeur d'une ou plusieurs colonnes d'une table
564 * @param string $table
565 * Type d'objet de la table (article)
566 * @param string|array $col
567 * Nom de la ou des colonnes (ps)
569 * Identifiant de l'objet
571 * Couples Nom de la colonne => Contenu de la colonne
573 function valeur_colonne_table($table, $col, $id) {
577 if (function_exists($f = $table.'_valeur_colonne_table_dist')
578 OR function_exists($f = $table.'_valeur_colonne_table')
579 OR $f = 'valeur_colonne_table_dist')
580 return $f($table, $col, $id);
584 * Extrait la valeur d'une configuration en meta
586 * Pour ces données, il n'y a toujours qu'une colonne (valeur),
587 * mais on gère l'enregistrement et la lecture via lire_config ou ecrire_config
588 * dès que l'on demande des sous parties d'une configuration.
590 * On ne retourne alors ici dans 'valeur' que la sous-partie demandée si
593 * @param string $table
594 * Nom de la table (meta)
596 * Nom des colonnes (valeur)
598 * Nom ou clé de configuration (descriptif_site ou demo__truc pour demo/truc)
600 * Couple valeur => Contenu de la configuration
602 function meta_valeur_colonne_table_dist($table, $col, $id) {
603 // Certaines clés de configuration sont echapées ici (cf #EDIT_CONFIG{demo/truc})
604 $id = str_replace('__', '/', $id);
606 // Éviter de planter les vieux SPIP
607 if (false === strpos($id, '/')) {
608 $config = isset($GLOBALS['meta'][$id]) ?
$GLOBALS['meta'][$id] : '';
609 // SPIP 3 ou Bonux 2 ou CFG
611 include_spip('inc/config');
612 $config = lire_config($id, '');
614 return array('valeur' => $config);
618 function return_log($var) {
619 die(crayons_json_export(array('$erreur'=> var_export($var,true))));
622 function _U($texte, $params=array()) {
623 include_spip('inc/charsets');
624 return unicode2charset(html2unicode(_T($texte, $params)));
628 * Obtenir la configuration des crayons
630 * @note wdgcfg = widget config :-)
633 * Couples : attribut => valeur
636 $php = function_exists('crayons_config') ?
crayons_config() : array();
637 include_spip('inc/meta');
640 $metacrayons = empty($meta['crayons']) ?
array() : unserialize($meta['crayons']);
643 'msgNoChange' => false,
644 'msgAbandon' => false, /* etait: true */
646 'yellow_fade' => false,
647 'clickhide' => false /* etait: true */
650 $wdgcfg[$cfgi] = isset($php[$cfgi]) ?
$php[$cfgi] :
651 isset($metacrayons[$cfgi]) ?
$metacrayons[$cfgi] : $def;
656 function &crayons_get_table($type, &$nom_table) {
657 list($distant,$table) = distant_table($type);
658 static $return = array();
659 static $noms = array();
660 if (!isset($return[$table])) {
661 $try = array(table_objet_sql($table), 'spip_'.table_objet($table), 'spip_' . $table . 's', $table . 's', 'spip_' . $table, $table);
663 // premiere possibilite (à partir de 1.9.3) : regarder directement la base
664 if (function_exists('sql_showtable')) {
665 foreach ($try as $nom) {
666 if ($q = sql_showtable($nom , !$distant , $distant)) {
667 $noms[$table] = $nom;
668 $return[$table] = $q;
674 // seconde, une heuristique 1.9.2
675 if (!isset($return[$table])) {
676 include_spip('base/serial');
677 include_spip('base/auxiliaires');
678 include_spip('public/parametrer');
679 foreach(array('tables_principales', 'tables_auxiliaires') as $categ) {
680 foreach ($try as $nom) {
681 if (isset($GLOBALS[$categ][$nom])) {
682 $noms[$table] = $nom;
683 $return[$table] = & $GLOBALS[$categ][$nom];
691 $nom_table = $noms[$table];
692 return $return[$table];
695 function distant_table($type) {
696 //separation $type en $distant $table
697 //separateur double underscore "__"
698 strstr($type,'__')?
list($distant,$table) = explode('__',$type) : list($distant,$table) = array(False,$type);
699 return array($distant,$table);