[PLUGINS] +crayons et enluminures
[ptitvelo/web/www.git] / www / plugins / crayons / crayons_fonctions.php
1 <?php
2 /**
3 * Crayons plugin for spip (c) Fil, toggg 2006-2013 -- licence GPL
4 *
5 * @package SPIP\Crayons\Fonctions
6 */
7 if (!defined("_ECRIRE_INC_VERSION")) return;
8
9 /**
10 * Débuguer les crayons
11 * mettre a true dans mes_options pour avoir les crayons non compresses
12 */
13 if(!defined('_DEBUG_CRAYONS'))
14 define('_DEBUG_CRAYONS', false);
15
16 // Dire rapidement si ca vaut le coup de chercher des droits
17 function analyse_droits_rapide_dist() {
18 return isset($GLOBALS['auteur_session']['statut']);
19 }
20
21 // Le pipeline header_prive (pour y tester les crayons)
22 function Crayons_insert_head($head) {
23 // verifie la presence d'une meta crayons, si c'est vide
24 // on ne cherche meme pas a traiter l'espace prive
25 $config_espace_prive = @unserialize($GLOBALS['meta']['crayons']);
26 if (empty($config_espace_prive)) {
27 return $head;
28 }
29
30 // verifie que l'edition de l'espace prive est autorisee
31 if ($config_espace_prive['espaceprive'] == 'on') {
32 // determine les pages (exec) crayonnables
33 if (($config_espace_prive['exec_autorise'] == '*') ||
34 in_array(_request('exec'),explode(',',$config_espace_prive['exec_autorise']))) {
35 // Calcul des droits
36 include_spip('inc/crayons');
37 $head = Crayons_preparer_page($head, '*', wdgcfg(), 'head');
38 }
39 }
40
41 // retourne l'entete modifiee
42 return $head;
43 }
44
45 // Le pipeline affichage_final, execute a chaque hit sur toute la page
46 function &Crayons_affichage_final(&$page) {
47
48 // ne pas se fatiguer si le visiteur n'a aucun droit
49 if (!(function_exists('analyse_droits_rapide')?analyse_droits_rapide():analyse_droits_rapide_dist()))
50 return $page;
51
52 // sinon regarder rapidement si la page a des classes crayon
53 if (strpos($page, 'crayon')===FALSE)
54 return $page;
55
56 // voir un peu plus precisement lesquelles
57 include_spip('inc/crayons');
58 if (!preg_match_all(_PREG_CRAYON, $page, $regs, PREG_SET_ORDER))
59 return $page;
60 $wdgcfg = wdgcfg();
61
62 // calculer les droits sur ces crayons
63 include_spip('inc/autoriser');
64 $droits = array();
65 $droits_accordes = 0;
66 foreach ($regs as $reg) {
67 list(,$crayon,$type,$champ,$id) = $reg;
68 if (_DEBUG_CRAYONS) spip_log("autoriser('modifier', $type, $id, NULL, array('champ'=>$champ))","crayons_distant");
69 if (autoriser('modifier', $type, $id, NULL, array('champ'=>$champ))) {
70 if(!isset($droits['.' . $crayon]))
71 $droits['.' . $crayon] = 0;
72 $droits['.' . $crayon]++;
73 $droits_accordes ++;
74 }
75 }
76 // et les signaler dans la page
77 if ($droits_accordes == count($regs)) // tous les droits
78 $page = Crayons_preparer_page($page, '*', $wdgcfg);
79 else if ($droits) // seulement certains droits, preciser lesquels
80 $page = Crayons_preparer_page($page, join(',',array_keys($droits)), $wdgcfg);
81
82 return $page;
83 }
84
85 function &Crayons_preparer_page(&$page, $droits, $wdgcfg = array(), $mode='page') {
86 /**
87 * Si pas forcer_lang, on charge le contrôleur dans la langue que l'utilisateur a dans le privé
88 */
89 if(!isset($GLOBALS['forcer_lang']) OR !$GLOBALS['forcer_lang'] OR ($GLOBALS['forcer_lang'] === 'non'))
90 lang_select($GLOBALS['auteur_session']['lang']);
91
92 $jsFile = generer_url_public('crayons.js');
93 if (_DEBUG_CRAYONS)
94 $jsFile = parametre_url($jsFile,'debug_crayons',1,'&');
95 include_spip('inc/filtres'); // rien que pour direction_css() :(
96 $cssFile = direction_css(find_in_path('crayons.css'));
97
98 $config = crayons_var2js(array(
99 'imgPath' => dirname(find_in_path('images/crayon.png')),
100 'droits' => $droits,
101 'dir_racine' => _DIR_RACINE,
102 'self' => self('&'),
103 'txt' => array(
104 'error' => _U('crayons:svp_copier_coller'),
105 'sauvegarder' => $wdgcfg['msgAbandon'] ? _U('crayons:sauvegarder') : ''
106 ),
107 'img' => array(
108 'searching' => array(
109 'txt' => _U('crayons:veuillez_patienter')
110 ),
111 'crayon' => array(
112 'txt' => _U('crayons:editer')
113 ),
114 'edit' => array(
115 'txt' => _U('crayons:editer_tout')
116 ),
117 'img-changed' => array(
118 'txt' => _U('crayons:deja_modifie')
119 )
120 ),
121 'cfg' => $wdgcfg
122 ));
123
124
125 // Est-ce que PortePlume est la ?
126 $meta_crayon = isset($GLOBALS['meta']['crayons']) ? unserialize($GLOBALS['meta']['crayons']): array();
127 $pp = '';
128 if (isset($meta_crayon['barretypo']) && $meta_crayon['barretypo']) {
129 if (function_exists('chercher_filtre')
130 AND $f = chercher_filtre('info_plugin')
131 AND $f('PORTE_PLUME','est_actif')) {
132
133 $pp = <<<EOF
134 cQuery(function() {
135 if (typeof onAjaxLoad == 'function') {
136 function barrebouilles_crayons() {
137 $('.formulaire_crayon textarea.crayon-active')
138 .barre_outils('edition');
139 }
140 onAjaxLoad(barrebouilles_crayons);
141 }
142 });
143 EOF;
144
145 }
146 }
147
148
149 $incCSS = "<link rel=\"stylesheet\" href=\"{$cssFile}\" type=\"text/css\" media=\"all\" />";
150 $incJS = <<<EOH
151 <script type="text/javascript">/* <![CDATA[ */
152 var configCrayons;
153 function startCrayons() {
154 configCrayons = new cQuery.prototype.cfgCrayons({$config});
155 cQuery.fn.crayonsstart();
156 {$pp}
157 }
158 var cr = document.createElement('script');
159 cr.type = 'text/javascript'; cr.async = true;
160 cr.src = '{$jsFile}\x26callback=startCrayons';
161 var s = document.getElementsByTagName('script')[0];
162 s.parentNode.insertBefore(cr, s);
163 /* ]]> */</script>
164
165 EOH;
166
167 if ($mode == 'head')
168 return $page . $incJS . $incCSS; //js inline avant les css, sinon ca bloque le chargement
169
170 $pos_head = strpos($page, '</head>');
171 if ($pos_head === false)
172 return $page;
173
174 // js inline avant la premiere css, ou sinon avant la fin du head
175 $pos_link = strpos($page, '<link ');
176 if (!$pos_link)
177 $pos_link = $pos_head;
178 $page = substr_replace($page, $incJS, $pos_link, 0);
179
180 // css avant la fin du head
181 $pos_head = strpos($page, '</head>');
182 $page = substr_replace($page, $incCSS, $pos_head, 0);
183
184 return $page;
185 }
186
187
188 /**
189 * Balise indiquant un champ SQL crayonnable
190 *
191 * @note
192 * Si cette fonction est absente, balise_EDIT_dist() déclarée par SPIP
193 * ne retourne rien
194 *
195 * @example
196 * <div class="#EDIT{texte}">#TEXTE</div>
197 * <div class="#EDIT{ps}">#PS</div>
198 *
199 * @param Champ $p
200 * Pile au niveau de la balise
201 * @return Champ
202 * Pile complétée par le code à générer
203 **/
204 function balise_EDIT($p) {
205
206 // le code compile de ce qui se trouve entre les {} de la balise
207 $label = interprete_argument_balise(1,$p);
208
209 // Verification si l'on est dans le cas d'une meta
210 // #EDIT{meta-descriptif_site} ou #EDIT{meta-demo/truc}
211 if (preg_match('/meta-(.*)\'/',$label,$meta)) {
212 $type = 'meta';
213 $label= 'valeur';
214 $primary = $meta[1];
215 $p->code = "classe_boucle_crayon('"
216 . $type
217 ."',"
218 .sinon($label,"''")
219 .","
220 . "str_replace('/', '__', '$primary')" # chaque / doit être remplacé pour CSS.
221 .").' '";
222 $p->interdire_scripts = false;
223 return $p;
224 }
225
226 $i_boucle = $p->nom_boucle ? $p->nom_boucle : $p->id_boucle;
227 // #EDIT hors boucle? ne rien faire
228 if (!$type = ($p->boucles[$i_boucle]->type_requete)) {
229 $p->code = "''";
230 $p->interdire_scripts = false;
231 return $p;
232 }
233
234 // crayon sur une base distante 'nua:article-intro-5'
235 if ($distant = $p->boucles[$i_boucle]->sql_serveur)
236 $type = $distant.'__'.$type;
237
238 // le compilateur 1.9.2 ne calcule pas primary pour les tables secondaires
239 // il peut aussi arriver une table sans primary (par ex: une vue)
240 if(!($primary = $p->boucles[$i_boucle]->primary)){
241 include_spip('inc/vieilles_defs'); # 1.9.2 pour trouver_def_table
242 list($nom, $desc) = trouver_def_table(
243 $p->boucles[$i_boucle]->type_requete, $p->boucles[$i_boucle]);
244 $primary = $desc['key']['PRIMARY KEY'];
245 }
246
247 $primary = explode(',',$primary);
248 $id = array();
249 foreach($primary as $key) {
250 $id[] = champ_sql(trim($key),$p);
251 }
252 $primary = implode(".'-'.",$id);
253
254 $p->code = "classe_boucle_crayon('"
255 . $type
256 ."',"
257 .sinon($label,"''")
258 .","
259 . $primary
260 .").' '";
261 $p->interdire_scripts = false;
262 return $p;
263 }
264
265
266 /**
267 * Balise indiquant une configuration crayonnable
268 *
269 * @example
270 * <div class="#EDIT_CONFIG{descriptif_site}">#DESCRIPTIF_SITE_SPIP</div>
271 * <div class="#EDIT_CONFIG{demo/truc}">#CONFIG{demo/truc}</div>
272 *
273 * @param Champ $p
274 * Pile au niveau de la balise
275 * @return Champ
276 * Pile complétée par le code à générer
277 **/
278 function balise_EDIT_CONFIG_dist($p) {
279
280 // le code compile de ce qui se trouve entre les {} de la balise
281 $config = interprete_argument_balise(1,$p);
282 if (!$config) return $p;
283
284 // chaque / du nom de config doit être transformé pour css.
285 // nous utiliserons '__' à la place.
286
287 $type = 'meta';
288 $label= 'valeur';
289
290 $p->code = "classe_boucle_crayon('"
291 . $type
292 . "','"
293 . $label
294 . "',"
295 . "str_replace('/', '__', $config)"
296 . ").' '";
297 $p->interdire_scripts = false;
298 return $p;
299 }
300
301 /**
302 * Crée le controleur du crayon indiqué par la classe CSS
303 *
304 * @param string $class
305 * Class CSS de crayon tel que créé par #EDIT
306 * @return string
307 * HTML du crayon, sinon texte d'erreur
308 **/
309 function creer_le_crayon($class) {
310 include_spip('inc/crayons');
311 include_spip('action/crayons_html');
312 $a = affiche_controleur($class, array('w' => 485, 'h' => 300, 'wh' => 500));
313 return $a['$erreur'] ? $a['$erreur'] : $a['$html'];
314 }
315
316 /**
317 * Balise #CRAYON affichant un formulaire de crayon
318 * SI ?edit=1;
319 *
320 * @example
321 * #CRAYON{ps}
322 *
323 * @param Champ $p
324 * Pile au niveau de la balise
325 * @return Champ
326 * Pile complétée par le code à générer
327 **/
328 function balise_CRAYON($p) {
329 $p = balise_EDIT($p);
330 $p->code = 'creer_le_crayon('.$p->code.')';
331 return $p;
332 }
333
334
335 /**
336 * Donne la classe CSS crayon en fonction
337 * - du type de la boucle
338 * (attention aux exceptions pour #EDIT dans les boucles HIERARCHIE et SITES)
339 * - du champ demande (vide, + ou se terminant par + : (+)classe type--id)
340 * - de l'id courant
341 *
342 * @param string $type
343 * Type d'objet, ou "meta" pour un champ de configuration
344 * @param string $champ
345 * Champ SQL concerné
346 * @param int|string $id
347 * Identifiant de la ligne sql
348 * @return string
349 * Classes CSS (à ajouter dans le HTML à destination du javascript de Crayons)
350 **/
351 function classe_boucle_crayon($type, $champ, $id) {
352 // $type = objet_type($type);
353 $type = $type[strlen($type) - 1] == 's' ?
354 substr($type, 0, -1) :
355 str_replace(
356 array('hierarchie', 'syndication'),
357 array('rubrique', 'site'),
358 $type);
359
360 $plus = (substr($champ, -1) == '+' AND $champ = substr($champ, 0, -1))
361 ? " $type--$id"
362 : '';
363
364 // test rapide pour verifier que l'id est valide (a-zA-Z0-9)
365 if (false !== strpos($id, ' ')) {
366 spip_log("L'identifiant ($id) ne pourra être géré ($type | $champ)", 'crayons');
367 return 'crayon_id_ingerable';
368 }
369
370 return 'crayon ' . $type . '-' . $champ . '-' . $id . $plus;
371 }
372
373 ?>