Passed
Push — master ( 9b7863...38c1f2 )
by Dispositif
07:54
created

OuvrageOptimize::predictPublisherWikiTitle()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 1
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of dispositif/wikibot application
4
 * 2019 : Philippe M. <[email protected]>
5
 * For the full copyright and MIT license information, please view the LICENSE file.
6
 */
7
8
declare(strict_types=1);
9
10
namespace App\Domain;
11
12
use App\Domain\Enums\Language;
13
use App\Domain\Models\Wiki\GoogleLivresTemplate;
14
use App\Domain\Publisher\GoogleBooksUtil;
15
use App\Domain\Utils\TextUtil;
16
use App\Domain\Utils\WikiTextUtil;
17
use App\Infrastructure\FileManager;
18
use DomainException;
19
use Exception;
20
21
/**
22
 * Legacy.
23
 * TODO move methods to OuvrageClean setters
24
 * TODO AbstractProcess
25
 * TODO observer/event (log, MajorEdition)
26
 * Class OuvrageProcess.
27
 */
28
class OuvrageOptimize extends AbstractTemplateOptimizer
29
{
30
    use OptimizeISBNTrait;
31
32
    const CONVERT_GOOGLEBOOK_TEMPLATE = false; // change OuvrageOptimizeTest !!
33
34
    const WIKI_LANGUAGE = 'fr';
35
36
    const PUBLISHER_FRWIKI_FILENAME = __DIR__.'/resources/data_editors_wiki.json';
37
38
    public $notCosmetic = false;
39
40
    public $major = false;
41
42
    /**
43
     * @return $this
44
     * @throws Exception
45
     */
46
    public function doTasks(): self
47
    {
48
        $this->cleanAndPredictErrorParameters();
49
50
        $this->processAuthors();
51
52
        $this->processLang();
53
        $this->processLang('langue originale');
54
55
        $this->processTitle();
56
        $this->convertLienAuteurTitre();
57
        $this->processEditeur();
58 47
        $this->processDates();
59
        $this->externalTemplates();
60 47
        $this->predictFormatByPattern();
61 47
62 47
        $this->processIsbn();
63 47
        $this->processBnf();
64 47
65
        $this->processLocation(); // 'lieu'
66
67
        $this->GoogleBookURL('lire en ligne');
68
        $this->GoogleBookURL('présentation en ligne');
69
70 47
        return $this;
71
    }
72 47
73
    /**
74 47
     * Todo: injection dep.
75
     * Todo : "[s. l.]" sans lieu "s.l.n.d." sans lieu ni date.
76 47
     *
77 47
     * @throws Exception
78
     */
79 47
    protected function processLocation()
80 47
    {
81 47
        $location = $this->getParam('lieu');
82 47
        if (empty($location)) {
83 47
            return;
84 47
        }
85
86 47
        // typo and unwikify
87 47
        $memo = $location;
88
        $location = WikiTextUtil::unWikify($location);
89 47
        $location = TextUtil::mb_ucfirst($location);
90
        if ($memo !== $location) {
91 47
            $this->setParam('lieu', $location);
92 47
            $this->addSummaryLog('±lieu');
93
            $this->notCosmetic = true;
94 47
        }
95
96
        // translation : "London"->"Londres"
97
        $manager = new FileManager();
98
        $row = $manager->findCSVline(__DIR__.'/resources/traduction_ville.csv', $location);
99
        if (!empty($row) && !empty($row[1])) {
100
            $this->setParam('lieu', $row[1]);
101
            $this->addSummaryLog('lieu francisé');
102
            $this->notCosmetic = true;
103 47
        }
104
    }
105 47
106 47
    protected function processBnf()
107 42
    {
108
        $bnf = $this->getParam('bnf');
109
        if (!$bnf) {
110
            return;
111 5
        }
112 5
        $bnf = str_ireplace('FRBNF', '', $bnf);
113 5
        $this->setParam('bnf', $bnf);
114 5
    }
115 1
116 1
    /**
117 1
     * @throws Exception
118
     */
119
    protected function processAuthors()
120
    {
121 5
        $this->distinguishAuthors();
122 5
        //$this->fusionFirstNameAndName(); // desactived : no consensus
123
    }
124 1
125 1
    protected function convertLienAuteurTitre(): void
126 1
    {
127 1
        $auteurParams = ['auteur1', 'auteur2', 'auteur2', 'titre'];
128 1
        foreach ($auteurParams as $auteurParam) {
129 1
            if ($this->hasParamValue($auteurParam)
130
                && $this->hasParamValue('lien '.$auteurParam)
131
            ) {
132 5
                $this->setParam(
133
                    $auteurParam,
134 47
                    WikiTextUtil::wikilink(
135
                        $this->getParam($auteurParam),
136 47
                        $this->getParam('lien '.$auteurParam)
137 47
                    )
138 46
                );
139
                $this->unsetParam('lien '.$auteurParam);
140 1
            }
141 1
        }
142 1
    }
143
144
    /**
145
     * Detect and correct multiple authors in same parameter.
146
     * Like "auteurs=J. M. Waller, M. Bigger, R. J. Hillocks".
147 47
     *
148
     * @throws Exception
149 47
     */
150
    protected function distinguishAuthors()
151 47
    {
152
        // merge params of author 1
153 47
        $auteur1 = $this->getParam('auteur') ?? '';
154
        $auteur1 .= $this->getParam('auteurs') ?? '';
155 47
        $auteur1 .= $this->getParam('prénom1') ?? '';
156 47
        $auteur1 .= ' '.$this->getParam('nom1') ?? '';
157 47
        $auteur1 = trim($auteur1);
158 47
        // of authors 2
159
        $auteur2 = $this->getParam('auteur2') ?? '';
160 1
        $auteur2 .= $this->getParam('prénom2') ?? '';
161 1
        $auteur2 .= ' '.$this->getParam('nom2') ?? '';
162 1
        $auteur2 = trim($auteur2);
163 1
164 1
        // skip if wikilink in author
165
        if (empty($auteur1) || WikiTextUtil::isWikify($auteur1)) {
166
            return;
167 1
        }
168
169
        $machine = new PredictAuthors();
170 47
        $res = $machine->predictAuthorNames($auteur1);
171
172
        if (1 === count($res)) {
173
            // auteurs->auteur?
174
            return;
175
        }
176
        // Many authors... and empty "auteur2"
177
        if (count($res) >= 2 && empty($auteur2)) {
178 47
            // delete author-params
179
            array_map(
180
                function ($param) {
181 47
                    $this->unsetParam($param);
182 47
                },
183 47
                ['auteur', 'auteurs', 'prénom1', 'nom1']
184 47
            );
185 47
            // iterate and edit new values
186
            $count = count($res);
187 47
            for ($i = 0; $i < $count; ++$i) {
188 47
                $this->setParam(sprintf('auteur%s', $i + 1), $res[$i]);
189 47
            }
190 47
            $this->addSummaryLog('distinction auteurs');
191
            $this->major = true;
192
            $this->notCosmetic = true;
193 47
        }
194 42
    }
195
196
    /**
197 5
     * todo: move/implement.
198 5
     *
199
     * @param string|null $param
200 5
     *
201
     * @throws Exception
202 3
     */
203
    protected function processLang(?string $param = 'langue')
204
    {
205 2
        $lang = $this->getParam($param) ?? null;
0 ignored issues
show
Bug introduced by
It seems like $param can also be of type null; however, parameter $name of App\Domain\AbstractTemplateOptimizer::getParam() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

205
        $lang = $this->getParam(/** @scrutinizer ignore-type */ $param) ?? null;
Loading history...
206
207 1
        if ($lang) {
208
            $lang2 = Language::all2wiki($lang);
209 1
210 1
            // strip "langue originale=fr"
211 1
            if ('langue originale' === $param && self::WIKI_LANGUAGE === $lang2
212
                && (!$this->getParam('langue') || $this->getParam('langue') === $lang2)
213
            ) {
214 1
                $this->unsetParam('langue originale');
215 1
                $this->addSummaryLog('-langue originale');
216 1
            }
217
218 1
            if ($lang2 && $lang !== $lang2) {
219 1
                $this->setParam($param, $lang2);
220 1
                if (self::WIKI_LANGUAGE !== $lang2) {
221
                    $this->addSummaryLog('±'.$param);
222 2
                }
223
            }
224
        }
225
    }
226
227
    /**
228
     * Find year of book publication.
229
     *
230
     * @return int|null
231 47
     * @throws Exception
232
     */
233 47
    protected function findBookYear(): ?int
234
    {
235 47
        $annee = $this->getParam('année');
236 6
        if (!empty($annee) && is_numeric($annee)) {
237
            return intval($annee);
238
        }
239 6
        $date = $this->getParam('date');
240 6
        if ($date && preg_match('#[^0-9]?([12][0-9][0-9][0-9])[^0-9]?#', $date, $matches) > 0) {
241
            return intval($matches[1]);
242 1
        }
243 1
244
        return null;
245
    }
246 6
247 4
    protected function stripIsbn(string $isbn): string
248 4
    {
249 3
        return trim(preg_replace('#[^0-9Xx]#', '', $isbn));
250
    }
251
252
    protected function processTitle()
253 47
    {
254
        $oldtitre = $this->getParam('titre');
255
        $this->langInTitle();
256
        $this->deWikifyExternalLink('titre');
257
        $this->upperCaseFirstLetter('titre');
258
        $this->typoDeuxPoints('titre');
259
260 47
        $this->extractSubTitle();
261
262 47
        // 20-11-2019 : Retiré majuscule à sous-titre
263 47
264 37
        if ($this->getParam('titre') !== $oldtitre) {
265
            $this->addSummaryLog('±titre');
266
        }
267
268 10
        $this->valideNumeroChapitre();
269 10
        $this->deWikifyExternalLink('titre chapitre');
270
        $this->upperCaseFirstLetter('titre chapitre');
271
    }
272 2
273 2
    protected function detectColon($param): bool
274 2
    {
275 2
        // > 0 don't count a starting colon ":bla"
276 2
        if ($this->hasParamValue($param) && mb_strrpos($this->getParam('titre'), ':') > 0) {
277 2
            return true;
278
        }
279
280
        return false;
281
    }
282
283
    protected function extractSubTitle(): void
284
    {
285
        // FIXED bug [[fu:bar]]
286
        if (!$this->getParam('titre') || WikiTextUtil::isWikify($this->getParam('titre'))) {
287
            return;
288
        }
289
290 2
        if (!$this->detectColon('titre')) {
291
            return;
292
        }
293
        // Que faire si déjà un sous-titre ?
294 8
        if ($this->hasParamValue('sous-titre')) {
295 8
            return;
296 7
        }
297 1
298
        // titre>5 and sous-titre>5 and sous-titre<40
299
        if (preg_match('#^(?<titre>[^:]{5,}):(?<st>.{5,40})$#', $this->getParam('titre'), $matches) > 0) {
300 1
            $this->setParam('titre', trim($matches['titre']));
301 1
            $this->setParam('sous-titre', trim($matches['st']));
302 1
            $this->addSummaryLog('>sous-titre');
303
        }
304 1
    }
305 1
306
    /**
307
     * Normalize a Google Book links.
308 1
     * Clean the useless URL parameters or transform into wiki-template.
309
     *
310
     * @param $param
311
     *
312 7
     * @throws Exception
313 7
     */
314 7
    protected function googleBookUrl(string $param): void
315
    {
316 1
        $url = $this->getParam($param);
317
        if (empty($url)
318
            || !GoogleBooksUtil::isGoogleBookURL($url)
319
        ) {
320 7
            return;
321 7
        }
322
323 4
        if (self::CONVERT_GOOGLEBOOK_TEMPLATE) {
324
            $template = GoogleLivresTemplate::createFromURL($url);
325
            if ($template) {
326 4
                $this->setParam($param, $template->serialize());
327
                $this->addSummaryLog('{Google}');
328
                $this->notCosmetic = true;
329
330
                return;
331
            }
332 4
        }
333 4
334
        try {
335
            $goo = GoogleBooksUtil::simplifyGoogleUrl($url);
336 4
        } catch (DomainException $e) {
337 4
            // ID manquant ou malformé
338 4
            $errorValue = sprintf(
339
                '%s <!-- ERREUR %s -->',
340
                $url,
341
                $e->getMessage()
342
            );
343 4
            $this->setParam($param, $errorValue);
344
            $this->addSummaryLog('erreur URL');
345
            $this->notCosmetic = true;
346
            $this->major = true;
347
        }
348
349 7
        if (!empty($goo) && $goo !== $url) {
350 7
            $this->setParam($param, $goo);
351 7
            // cleaned tracking parameters in Google URL ?
352
            if (GoogleBooksUtil::isTrackingUrl($url)) {
353
                $this->addSummaryLog('tracking');
354 7
                $this->notCosmetic = true;
355
            }
356
        }
357
    }
358
359
    /**
360
     * - {{lang|...}} dans titre => langue=... puis titre nettoyé
361
     *  langue=L’utilisation de ce paramètre permet aussi aux synthétiseurs vocaux de reconnaître la langue du titre de
362 10
     * l’ouvrage.
363
     * Il est possible d'afficher plusieurs langues, en saisissant le nom séparé par des espaces ou des virgules. La première langue doit être celle du titre.
364 10
     *
365 10
     * @throws Exception
366 1
     */
367
    protected function langInTitle(): void
368 9
    {
369 9
        if (preg_match(
370 1
                '#^{{ ?(?:lang|langue) ?\| ?([a-z-]{2,5}) ?\| ?(?:texte=)?([^{}=]+)(?:\|dir=rtl)?}}$#i',
371
                $this->getParam('titre'),
372
                $matches
373 8
            ) > 0
374
        ) {
375
            $lang = trim($matches[1]);
376 9
            $newtitre = str_replace($matches[0], trim($matches[2]), $this->getParam('titre'));
377
378 9
            // problème : titre anglais de livre français
379
            // => conversion {{lang}} du titre seulement si langue= défini
380
            // opti : restreindre à ISBN zone 2 fr ?
381 47
            if ($lang === $this->getParam('langue')) {
382
                $this->setParam('titre', $newtitre);
383 47
                $this->addSummaryLog('°titre');
384 47
            }
385 47
386 47
            // desactivé à cause de l'exception décrite ci-dessus
387 47
            // si langue=VIDE : ajout langue= à partir de langue titre
388
            //            if (self::WIKI_LANGUAGE !== $lang && empty($this->getParam('langue'))) {
389 47
            //                $this->setParam('langue', $lang);
390
            //                $this->log('+langue='.$lang);
391
            //            }
392
        }
393 47
    }
394 5
395
    protected function processDates()
396
    {
397 47
        // dewikification
398 47
        $params = ['date', 'année', 'mois', 'jour'];
399 47
        foreach ($params as $param) {
400 47
            if ($this->hasParamValue($param) && WikiTextUtil::isWikify(' '.$this->getParam($param))) {
401
                $this->setParam($param, WikiTextUtil::unWikify($this->getParam($param)));
402 13
            }
403
        }
404
405 13
        try {
406 3
            $this->moveDate2Year();
407
        } catch (Exception $e) {
408
            $this->log->warning('Exception '.$e->getMessage());
409 10
        }
410
    }
411
412 47
    /**
413
     * Bool ?
414
     * déwikification du titre : consensus Bistro 27 août 2011
415 47
     * idem  'titre chapitre'.
416 34
     *
417
     * @param string $param
418
     *
419 13
     * @throws Exception
420 10
     */
421
    protected function deWikifyExternalLink(string $param): void
422
    {
423 3
        if (empty($this->getParam($param))) {
424
            return;
425
        }
426
        if (preg_match('#^\[(http[^ \]]+) ([^]]+)]#i', $this->getParam($param), $matches) > 0) {
427
            $this->setParam($param, str_replace($matches[0], $matches[2], $this->getParam($param)));
428 3
            $this->addSummaryLog('±'.$param);
429 3
430 3
            if (in_array($param, ['titre', 'titre chapitre'])) {
431 3
                if (empty($this->getParam('lire en ligne'))) {
432
                    $this->setParam('lire en ligne', $matches[1]);
433 3
                    $this->addSummaryLog('+lire en ligne');
434
435
                    return;
436
                }
437
                $this->addSummaryLog('autre lien externe: '.$matches[1]);
438
            }
439
        }
440
    }
441
442
    protected function upperCaseFirstLetter($param)
443 47
    {
444
        if (!$this->hasParamValue($param)) {
445 47
            return;
446 47
        }
447 47
        $newValue = TextUtil::mb_ucfirst(trim($this->getParam($param)));
448
        $this->setParam($param, $newValue);
449 47
    }
450
451
    /**
452 1
     * Typo internationale 'titre : sous-titre'.
453
     * Fix fantasy typo of subtitle with '. ' or ' - '.
454
     * International Standard Bibliographic Description :
455
     * https://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Le_Bistro/13_janvier_2016#Modif_du_mod%C3%A8le:Ouvrage.
456
     *
457
     * @param $param
458
     *
459
     * @throws Exception
460
     */
461
    protected function typoDeuxPoints($param)
462
    {
463
        $origin = $this->getParam($param) ?? '';
464 1
        if (empty($origin)) {
465
            return;
466
        }
467
        // FIXED bug [[fu:bar]]
468
        if (WikiTextUtil::isWikify($origin)) {
469
            return;
470
        }
471
472
        $origin = TextUtil::replaceNonBreakingSpaces($origin);
473
474
        $strTitle = $origin;
475
476
        // CORRECTING TYPO FANTASY OF SUBTITLE
477
478 1
        // Replace first '.' by ':' if no ': ' and no numbers around (as PHP 7.3)
479 1
        // exlude pattern "blabla... blabla"
480
        // TODO: statistics
481 1
482 1
        // Replace ' - ' or ' / ' (spaced!) by ' : ' if no ':' and no numbers after (as PHP 7.3 or 1939-1945)
483 1
        if (!mb_strpos(':', $strTitle) && preg_match('#.{6,} ?[-/] ?[^0-9)]{6,}#', $strTitle) > 0) {
484
            $strTitle = preg_replace('#(.{6,}) [-/] ([^0-9)]{6,})#', '$1 : $2', $strTitle);
485
        }
486 1
487
        // international typo style " : " (first occurrence)
488
        $strTitle = preg_replace('#[ ]*:[ ]*#', ' : ', $strTitle);
489
490
        if ($strTitle !== $origin) {
491
            $this->setParam($param, $strTitle);
492
            $this->addSummaryLog(sprintf(':%s', $param));
493
        }
494
    }
495
496 47
    protected function valideNumeroChapitre()
497
    {
498 47
        $value = $this->getParam('numéro chapitre');
499 47
        if (empty($value)) {
500 47
            return;
501 47
        }
502 47
        // "12" ou "VI", {{II}}, II:3
503
        if (preg_match('#^[0-9IVXL\-.:{}]+$#i', $value) > 0) {
504
            return;
505
        }
506
        // déplace vers "titre chapitre" ?
507
        if (!$this->getParam('titre chapitre')) {
508
            $this->unsetParam('numéro chapitre');
509
            $this->setParam('titre chapitre', $value);
510
        }
511
        $this->addSummaryLog('≠numéro chapitre');
512
    }
513
514
    /**
515
     * TODO move+refac
516
     * TODO CommentaireBiblioTemplate  ExtraitTemplate
517
     * Probleme {{commentaire biblio}} <> {{commentaire biblio SRL}}
518
     * Generate supplementary templates from obsoletes params.
519
     *
520
     * @throws Exception
521
     */
522 47
    protected function externalTemplates()
523
    {
524 47
        // "extrait=bla" => {{citation bloc|bla}}
525
        if ($this->hasParamValue('extrait')) {
526
            $extrait = $this->getParam('extrait');
527 47
            // todo bug {{citation bloc}} si "=" ou "|" dans texte de citation
528 47
            // Legacy : use {{début citation}} ... {{fin citation}}
529 47
            if (preg_match('#[=|]#', $extrait) > 0) {
530 1
                $this->optiTemplate->externalTemplates[] = (object)[
531
                    'template' => 'début citation',
532
                    '1' => '',
533
                    'raw' => '{{Début citation}}'.$extrait.'{{Fin citation}}',
534
                ];
535 47
                $this->addSummaryLog('{Début citation}');
536
                $this->notCosmetic = true;
537
            } else {
538
                // StdClass
539 47
                $this->optiTemplate->externalTemplates[] = (object)[
540
                    'template' => 'citation bloc',
541
                    '1' => $extrait,
542
                    'raw' => '{{Citation bloc|'.$extrait.'}}',
543
                ];
544
                $this->addSummaryLog('{Citation bloc}');
545
                $this->notCosmetic = true;
546
            }
547 47
548
            $this->unsetParam('extrait');
549 47
            $this->notCosmetic = true;
550 45
        }
551
552 2
        // "commentaire=bla" => {{Commentaire biblio|1=bla}}
553
        if ($this->hasParamValue('commentaire')) {
554 2
            $commentaire = $this->getParam('commentaire');
555 2
            $this->optiTemplate->externalTemplates[] = (object)[
556
                'template' => 'commentaire biblio',
557 1
                '1' => $commentaire,
558
                'raw' => '{{Commentaire biblio|'.$commentaire.'}}',
559
            ];
560
            $this->unsetParam('commentaire');
561 2
            $this->addSummaryLog('{commentaire}');
562
            $this->notCosmetic = true;
563
        }
564
    }
565
566
    // ----------------------
567 2
    // ----------------------
568 2
    // ----------------------
569 2
570
    /**
571 2
     * Date->année (nécessaire pour OuvrageComplete).
572
     *
573
     * @throws Exception
574
     */
575 2
    protected function moveDate2Year()
576 2
    {
577 2
        $date = $this->getParam('date') ?? false;
578 2
        if ($date) {
579 2
            if (preg_match('#^-?[12][0-9][0-9][0-9]$#', $date)) {
580 2
                $this->setParam('année', $date);
581 2
                $this->unsetParam('date');
582 2
                //$this->log('>année');
583
            }
584
        }
585
    }
586 2
587
    protected function predictFormatByPattern()
588
    {
589
        if (($value = $this->getParam('format'))) {
590
            // predict if 'format électronique'
591
            // format electronique lié au champ 'lire en ligne'
592
            // 2015 https://fr.wikipedia.org/wiki/Discussion_mod%C3%A8le:Ouvrage#format,_format_livre,_format_%C3%A9lectronique
593
            //            if (preg_match('#(pdf|epub|html|kindle|audio|\{\{aud|jpg)#i', $value) > 0) {
594
            //
595
            //                $this->setParam('format électronique', $value);
596 47
            //                $this->unsetParam('format');
597
            //                $this->log('format:électronique?');
598 47
            //
599
            //                return;
600
            //            }
601 47
            if (preg_match(
602
                    '#(ill\.|couv\.|in-[0-9]|in-fol|poche|broché|relié|{{unité|{{Dunité|[0-9]{2} ?cm|\|cm}}|vol\.|A4)#i',
603 47
                    $value
604
                ) > 0
605
            ) {
606 35
                $this->setParam('format livre', $value);
607
                $this->unsetParam('format');
608
                $this->addSummaryLog('format:livre?');
609 35
                $this->notCosmetic = true;
610 35
            }
611
            // Certainement 'format électronique'...
612 35
        }
613
    }
614 26
615
    /**
616 26
     * todo : vérif lien rouge
617 26
     * todo 'lien éditeur' affiché 1x par page
618
     * opti : Suppression lien éditeur si c'est l'article de l'éditeur.
619 26
     *
620
     * @throws Exception
621
     */
622
    protected function processEditeur()
623
    {
624
        $editeur = $this->getParam('éditeur');
625
        if (empty($editeur)) {
626
            return;
627
        }
628
629
        // FIX bug "GEO Art ([[Prisma Media]]) ; [[Le Monde]]"
630 47
        if (preg_match('#\[.*\[.*\[#', $editeur) > 0) {
631
            return;
632 47
        }
633 47
        // FIX bug "[[Fu|Bar]] bla" => [[Fu|Bar bla]]
634
        if (preg_match('#(.+\[\[|\]\].+)#', $editeur) > 0) {
635 15
            return;
636 1
        }
637 1
638
        // [[éditeur]]
639 1
        if (preg_match('#\[\[([^|]+)]]#', $editeur, $matches) > 0) {
640 1
            $editeurUrl = $matches[1];
641 1
        }
642 1
        // [[bla|éditeur]]
643
        if (preg_match('#\[\[([^]|]+)\|.+]]#', $editeur, $matches) > 0) {
644 1
            $editeurUrl = $matches[1];
645
        }
646
647
        // Todo : traitement/suppression des abréviations communes :
648
        // ['éd. de ', 'éd. du ', 'éd.', 'ed.', 'Éd. de ', 'Éd.', 'édit.', 'Édit.', '(éd.)', '(ed.)', 'Ltd.']
649 14
650
        $editeurStr = WikiTextUtil::unWikify($editeur);
651 47
        // On garde minuscule sur éditeur, pour nuance Éditeur/éditeur permettant de supprimer "éditeur"
652
        // ex: "éditions Milan" => "Milan"
653 47
654 47
        // Déconseillé : 'lien éditeur' (obsolete 2019)
655
        if ($this->hasParamValue('lien éditeur')) {
656 15
            if (empty($editeurUrl)) {
657 15
                $editeurUrl = $this->getParam('lien éditeur');
658 15
            }
659
            $this->unsetParam('lien éditeur');
660
        }
661
662
        if (empty($editeurUrl)) {
663
            $editeurUrl = $this->predictPublisherWikiTitle($editeurStr);
664
            if (!empty($editeurUrl) && $this->wikiPageTitle !== $editeurUrl) {
665
                $this->addSummaryLog('+lien éditeur');
666
                $this->notCosmetic = true;
667
                $this->major = true;
668
            }
669
        }
670 47
671
672 47
        $newEditeur = $editeurStr;
673 47
        if (!empty($editeurUrl)) {
674 32
            $newEditeur = WikiTextUtil::wikilink($editeurStr, $editeurUrl);
675
        }
676
677 15
        if ($newEditeur !== $editeur) {
678 2
            $this->setParam('éditeur', $newEditeur);
679
            $this->addSummaryLog('±éditeur');
680
            $this->notCosmetic = true;
681 13
        }
682
    }
683 13
684
    /**
685
     * todo move (cf. Article/Lien web optimizing)
686
     *
687
     * @param string $publisherName
688
     *
689
     * @return string|null
690
     */
691
    public function predictPublisherWikiTitle(string $publisherName): ?string
692 13
    {
693 4
        try {
694
            $data = json_decode(file_get_contents(self::PUBLISHER_FRWIKI_FILENAME), true);
695
        } catch (\Throwable $e) {
696
            $this->log->error('Catch EDITOR_TITLES_FILENAME import '.$e->getMessage());
697 13
        }
698
        if (isset($data[$publisherName])) {
699 13
            return (string)urldecode($data[$publisherName]);
700 3
        }
701 3
702
        return null;
703 13
    }
704
}
705