From bc14d5a7afaa2f62fc754d3f34acfc0691b9e1b1 Mon Sep 17 00:00:00 2001
From: efalcy <efalcy@afi-sa.fr>
Date: Fri, 2 Nov 2018 19:03:38 +0100
Subject: [PATCH] dev #79082 : add js to select url to convert to https and
 check boxes when url https is valid

---
 .../admin/controllers/AjaxController.php      |  11 ++
 .../admin/controllers/SearchController.php    |  10 --
 .../admin/views/scripts/search/list.phtml     | 170 +++++++++++-------
 library/Class/ContentTextReplacement.php      |  92 ++++++----
 .../controllers/SearchControllerTest.php      |  51 ++++++
 5 files changed, 226 insertions(+), 108 deletions(-)

diff --git a/application/modules/admin/controllers/AjaxController.php b/application/modules/admin/controllers/AjaxController.php
index a9ecf7aaafe..9373268e528 100644
--- a/application/modules/admin/controllers/AjaxController.php
+++ b/application/modules/admin/controllers/AjaxController.php
@@ -80,6 +80,17 @@ class Admin_AjaxController extends Zend_Controller_Action {
 
   }
 
+  public function forceHttpsAction() {
+    if (!($url = $this->_getParam('url')) && strlen($url) <10)
+      $this->redirect();
+
+    (new Class_ContentTextReplacement())->transformUrlToHttps(urldecode($url));
+    return $url;
+    $this->_redirect($this->view->url(['module' => 'admin',
+                                       'controller' => 'search',
+                                       'action' => 'list']));
+  }
+
 
   protected function _checkUrl($url) {
     $file_headers = @get_headers($url);
diff --git a/application/modules/admin/controllers/SearchController.php b/application/modules/admin/controllers/SearchController.php
index 4ba53ea56a0..65e0da22362 100644
--- a/application/modules/admin/controllers/SearchController.php
+++ b/application/modules/admin/controllers/SearchController.php
@@ -67,16 +67,6 @@ class Admin_SearchController extends ZendAfi_Controller_Action {
   }
 
 
-  public function forceHttpsAction() {
-    if (!($url = $this->_getParam('url')) && strlen($url) <10)
-      $this->redirect();
-
-    (new Class_ContentTextReplacement())->transformUrlToHttps(urldecode($url));
-    $this->_redirect($this->view->url(['module' => 'admin',
-                                       'controller' => 'search',
-                                       'action' => 'list']));
-  }
-
 
   protected function _searchForm() {
     return (new ZendAfi_Form())
diff --git a/application/modules/admin/views/scripts/search/list.phtml b/application/modules/admin/views/scripts/search/list.phtml
index 2d248ca99e6..391432c8ec3 100644
--- a/application/modules/admin/views/scripts/search/list.phtml
+++ b/application/modules/admin/views/scripts/search/list.phtml
@@ -1,54 +1,77 @@
 <?php
 
+$active = Class_Admin_Skin::current()->renderActionIconOn('active', $this, ['alt' => '']). ' ' . $this->_('Https');
 
+$inactive = Class_Admin_Skin::current()->renderActionIconOn('inactive', $this, ['alt' => '']). ' ' . $this->_('Https');
+
+
+ if ($this->only_baseurls)
+   echo $this->tagAnchor($this->url(['controller' => 'search',
+                                     'action' => 'list',
+                                     'base' => 0]), $this->_('Voir toutes les urls'));
+ if (!$this->only_baseurls)
+   echo $this->tagAnchor($this->url(['controller' => 'search',
+                                     'action' => 'list',
+                                     'base' => 1]), $this->_('Voir les domaines uniquement'));
+
+
+ $get_urls=[];
+ $get_urls_https = [];
+ $id=1;
+ $transfo = (new Class_ContentTextReplacement());
+ $urls = $transfo->findAllUrls($this->search,$this->preg);
+
+ $entities = [];
+
+ foreach ($urls as $key => $number) {
+   if (isset($entities[$key])) {
+     continue;
+   }
+
+   $entity = new Class_Entity();
+   $entity->setSize($number);
+   $entity->setId($id);
+
+   $entity->setType('Article');
+   $entity->setUrl($key);
+ $get_urls_https[] = 'getUrlHttps(\''.urlencode($key).'\','.$id.')';
+ $get_urls[] = 'getUrlHttp(\''.urlencode($key).'\',\'#id'.$id.'\')';
+ $id++;
+ $entities[$key] =$entity;
+ }
+
+ ?>
+
+<script>
+
+
+ function selectHttps(id) {
+   var sel = '#idselected'+id;
+
+   if ($(sel).hasClass('httpsselected')) {
+     $(sel+' a').html('<?php echo $inactive; ?>');
+                        return $(sel).removeClass('httpsselected');
+                        }
+  $(sel+' a').html('<?php echo $active; ?>');
+                     $(sel).addClass("httpsselected");
+
+ }
+
+
+ function convertHttps() {
+$( ".httpsselected" ).each(function() {
+
+     convertHttpToHttps($(this).attr('data-url'),$(this).attr('id'));
+   });
+
+ }
+
+</script>
 
-if ($this->only_baseurls)
-  echo $this->tagAnchor($this->url(['controller' => 'search',
-                                    'action' => 'list',
-                                    'base' => 0]), $this->_('Voir toutes les urls'));
-if (!$this->only_baseurls)
-  echo $this->tagAnchor($this->url(['controller' => 'search',
-                                    'action' => 'list',
-                                    'base' => 1]), $this->_('Voir les domaines uniquement'));
-
-
-$get_urls=[];
-$get_urls_https = [];
-$id=1;
-$transfo = (new Class_ContentTextReplacement());
-$urls = $transfo->findAllUrls($this->search,$this->preg);
-
-$entities = [];
-
-foreach ($urls as $key => $number) {
-  if (isset($entities[$key])) {
-    continue;
-  }
-
-  $entity = new Class_Entity();
-  $entity->setSize($number);
-  $entity->setId($id);
-
-  $entity->setType('Article');
-  $entity->setUrl($key);
-  /*  $get_urls[]= 'urlExists("'.$key.'",
-  function(success) {if (success) {
-  return  $(id'.$id.').append("OK");
-  } else {
-  return  $(this).append("NOK");
-
-  }})';
-   */
-  $get_urls_https[] = 'getUrlHttps(\''.urlencode($key).'\',\'#idhttps'.$id.'\')';
-  $get_urls[] = 'getUrlHttp(\''.urlencode($key).'\',\'#id'.$id.'\')';
-  $id++;
-  $entities[$key] =$entity;
-}
-
-//  Class_ScriptLoader::getInstance()
-//  ->addJQueryReady('
-?>
 <script>
+
+
+
  var  urlExists = function(url,callback) {
 
 
@@ -68,14 +91,17 @@ foreach ($urls as $key => $number) {
  };
 
  function getUrlHttps(url,id) {
+   var idhttps = '#idhttps'+id;
    $.ajax({
      url : "<?php echo BASE_URL; ?>/admin/ajax/test-url-https",
      type : "GET",
      data : "url="+url,
      dataType : "html",
      success : function(code_html, statut){
+       if (code_html.indexOf('error') < 0)
+       selectHttps(id);
+       return $(idhttps).append(code_html);
 
-       return $(id).append(code_html);
 
      }
    });
@@ -96,10 +122,22 @@ foreach ($urls as $key => $number) {
 
  }
 
+ function convertHttpToHttps(url,id) {
+   $.ajax({
+     url : "<?php echo BASE_URL; ?>/admin/ajax/force-https",
+     type : "GET",
+     data : "url="+encodeURIComponent(url),
+     dataType : "html",
+     success : function(code_html, statut){
+       return $('#'+id).html('OK');
+
+     }
+   });
+
+ }
+
 </script>
 <?php
-//');
-
 
 echo '<br/>'.$this->tagAnchor($this->url(['controller' => 'search',
                                           'action' => 'list',
@@ -117,16 +155,12 @@ echo '<br/>'.$this->tagAnchor($this->url(['controller' => 'search',
 
 echo '<br/>';
 
-
-//}
 ?>
 
 
 <?php
 
 
-
-
 $description = (new Class_TableDescription('urls'))
   ->addColumn($this->_('http'), function($feature)
               {
@@ -145,32 +179,38 @@ $description
 });
 
 
-$description ->addColumn($this->_('occurences'), function($feature)
-                         {
+$description ->addColumn($this->_('occurences'), function($feature) {
   return $this->tagAnchor($this->url(['controller' => 'search',
                                       'action' =>'detail',
                                       'url' => $feature->getUrl()
-]),
-                                      $feature->getSize());
+                                      ]),
+                          $feature->getSize());
 })
-             ->addRowAction(function($feature)
-                            {
-  return $this->tagAnchor($this->url(['controller' => 'search',
-                                      'action' => 'force-https',
-                                      'ids' => implode('-',$feature->getIds()),
-                                      'url' => $feature->getUrl()]),
-                          $this->_('Force HTTPS'));
+             ->addRowAction(function($feature) use ($inactive){
+  $link = $this->tagAnchor('',$inactive, ['onclick' => "selectHttps(".$feature->getId().");return false;"]);
+return $this->tag('div',$link
+           ,['id' => 'idselected'.$feature->getId(),                                                                                                                'data-url' => $feature->getUrl()]);});
+
 
 
-}) ;
 
 echo $this->renderForm($this->searchform);
 echo '<br/>';
 
 echo $this->renderForm($this->form);
 
+
+echo '<br/>'.$this->tagAnchor($this->url(['controller' => 'search',
+                                          'action' => 'list',
+                                          'testhttps' =>1 ]),
+                              $this->_('Convertir les urls selectionnées en HTTPS'),
+                              [ 'onclick' => "convertHttps();return false;" ]
+                              );
+
+
 echo $this->tag('div', $this->renderTable($description,
                                           $entities
                                           ));
 
+
 ?>
diff --git a/library/Class/ContentTextReplacement.php b/library/Class/ContentTextReplacement.php
index 49545e4514c..18799e87755 100644
--- a/library/Class/ContentTextReplacement.php
+++ b/library/Class/ContentTextReplacement.php
@@ -21,8 +21,6 @@
 
 
 class Class_ContentTextReplacement {
-
-
   public function transformUrlToHttps($url) {
     $this->replaceText($url,$this->_getHttps($url));
   }
@@ -30,21 +28,9 @@ class Class_ContentTextReplacement {
 
   public function replaceText($old_text,$new_text) {
     (new Class_ArticleReplacement())->replaceTextTo($old_text,$new_text);
-
   }
 
 
-  protected function mergeUrls($matches,$urls, $text) {
-    foreach($matches as $match) {
-      if (trim($match[0]) == ''|| (strpos($match[0], $text)===false))
-        continue;
-      if (isset($urls[$match[0]]))
-        $urls[$match[0]]=$urls[$match[0]]+1;
-      else $urls[$match[0]]=1;
-    }
-    return $urls;
-  }
-
   public function getArticles($text) {
     return (new Class_ArticleReplacement())->findAll($text);
   }
@@ -52,49 +38,59 @@ class Class_ContentTextReplacement {
 
   public function findAllUrls($http, $preg) {
     $urls = [];
-    foreach ( (new Class_ArticleReplacement())->findAll($http) as $article) {
-      preg_match_all($preg, $article->getContenu(), $matches, PREG_PATTERN_ORDER) ;
-      $urls =$this->mergeUrls($matches,$urls, $http);
-      preg_match_all($preg, $article->getDescription(), $matches, PREG_PATTERN_ORDER) ;
-      $urls =$this->mergeUrls($matches,$urls,$http);
+    $urls = (new Class_ArticleReplacement())->mergeUrl($http, $preg, $urls);
+    $urls = (new Class_NewsletterReplacement())->mergeUrl($http, $preg, $urls);
+    $urls = (new Class_DomainsReplacement())->mergeUrl($http, $preg, $urls);
 
-    }
-    foreach ((new Class_NewsletterReplacement())->findAll($http) as $model) {
-      preg_match_all($preg, $model->getContenu(), $matches, PREG_PATTERN_ORDER) ;
-      $urls =$this->mergeUrls($matches,$urls, $http);
-    }
-    foreach ((new Class_DomainsReplacement())->findAll($http) as $model) {
-      preg_match_all($preg, $model->getUrlImg(), $matches, PREG_PATTERN_ORDER) ;
-      $urls =$this->mergeUrls($matches,$urls, $http);
+    return $urls;
+  }
 
+  protected function mergeUrls($matches,$urls, $text) {
+    foreach($matches as $match) {
+      if (trim($match[0]) == ''|| (strpos($match[0], $text)===false))
+        continue;
+      if (isset($urls[$match[0]]))
+        $urls[$match[0]]=$urls[$match[0]]+1;
+      else $urls[$match[0]]=1;
     }
     return $urls;
   }
 
-
   protected function _getHttps($url) {
     return str_replace('http://','https://', $url);
   }
+}
 
 
 
-}
-
 
-abstract  class Class_ContentReplacement  {
+abstract class Class_ContentReplacement  {
   public function replaceTextTo($old_text,$new_text) {
     foreach ($this->findAll($old_text) as $model) {
       $this->_saveModel($model,$old_text,$new_text);
     }
+  }
 
+  protected function mergeUrls($matches,$urls, $text) {
+    foreach($matches as $match) {
+      if (trim($match[0]) == ''|| (strpos($match[0], $text)===false))
+        continue;
+      if (isset($urls[$match[0]]))
+        $urls[$match[0]]=$urls[$match[0]]+1;
+      else $urls[$match[0]]=1;
+    }
+    return $urls;
   }
+
+
   abstract protected function _saveModel($model,$old_text,$new_text);
 }
 
 
+
+
 class Class_ArticleReplacement extends Class_ContentReplacement {
   protected function _saveModel($article, $old_text,$new_text) {
-    echo str_ireplace($old_text,$new_text,$article->getContenu());
     $article->setContenu(str_ireplace($old_text,$new_text,$article->getContenu()));
     $article->setDescription(str_ireplace($old_text,$new_text,$article->getDescription()));
     $article->save();
@@ -105,11 +101,22 @@ class Class_ArticleReplacement extends Class_ContentReplacement {
     return Class_Article::findAllBy(['where' => 'concat(description,contenu) like "%'. $text .'%"']);
   }
 
+
+  public function mergeUrl($http, $preg, $urls) {
+    foreach ( $this->findAll($http) as $article) {
+      preg_match_all($preg, $article->getContenu(), $matches, PREG_PATTERN_ORDER) ;
+      $urls =$this->mergeUrls($matches,$urls, $http);
+      preg_match_all($preg, $article->getDescription(), $matches, PREG_PATTERN_ORDER) ;
+      $urls =$this->mergeUrls($matches,$urls,$http);
+    }
+    return $urls;
+  }
 }
 
 
-class Class_NewsletterReplacement extends Class_ContentReplacement {
 
+
+class Class_NewsletterReplacement extends Class_ContentReplacement {
   protected function _saveModel($model, $old_text,$new_text) {
     $model->setContenu(str_ireplace($old_text,$new_text,$article->getContenu()));
     $model->save();
@@ -119,9 +126,19 @@ class Class_NewsletterReplacement extends Class_ContentReplacement {
     return Class_Newsletter::findAllBy(['where' => 'contenu like "%' . $text . '%"']);
   }
 
+  public function mergeUrl($http, $preg, $urls) {
+    foreach ($this->findAll($http) as $model) {
+      preg_match_all($preg, $model->getContenu(), $matches, PREG_PATTERN_ORDER) ;
+      $urls =$this->mergeUrls($matches,$urls, $http);
+    }
+    return $urls;
+  }
+
 }
 
 
+
+
 class Class_DomainsReplacement extends Class_ContentReplacement {
   protected function _saveModel($model, $old_text,$new_text) {
     $model->setUrlImg(str_ireplace($old_text,$new_text,$model->getUrlImg()));
@@ -131,5 +148,14 @@ class Class_DomainsReplacement extends Class_ContentReplacement {
   public function findAll($text) {
     return Class_Catalogue::findAllBy(['where' => 'url_img like "%' . $text . '%"']);
   }
+
+  public function mergeUrl($http, $preg, $urls) {
+    foreach ($this->findAll($http) as $model) {
+      preg_match_all($preg, $model->getUrlImg(), $matches, PREG_PATTERN_ORDER) ;
+      $urls =$this->mergeUrls($matches,$urls, $http);
+
+    }
+    return $urls;
+  }
 }
 ?>
\ No newline at end of file
diff --git a/tests/application/modules/admin/controllers/SearchControllerTest.php b/tests/application/modules/admin/controllers/SearchControllerTest.php
index a6604ccda8e..bf4741f537f 100644
--- a/tests/application/modules/admin/controllers/SearchControllerTest.php
+++ b/tests/application/modules/admin/controllers/SearchControllerTest.php
@@ -63,3 +63,54 @@ class SearchControllerPostTest extends Admin_AbstractControllerTestCase {
 
 
 }
+
+
+
+
+class SearchControllerForceHttpsPostTest extends Admin_AbstractControllerTestCase {
+  protected $_storm_default_to_volatile = true;
+
+  public function setUp() {
+    parent::setUp();
+
+    ZendAfi_Auth::getInstance()
+      ->logUser($this->fixture('Class_Users',
+                               ['id' => 6,
+                                'login' => 'sysadm',
+                                'password' => 123,
+                                'role_level' => ZendAfi_Acl_AdminControllerRoles::SUPER_ADMIN]));
+
+        $this->fixture('Class_Notice',
+                   ['id' => 123910,
+                    'alpha_titre' => 'LANGUE NON SPECIFIEE',
+                    'type_doc' => Class_TypeDoc::ARTICLE]);
+
+
+    $this->onLoaderOfModel('Class_Article')
+         ->whenCalled('findAllBy')
+         ->answers([$this->fixture('Class_Article',['id' => 4,
+                                                    'id_notice' => 123910,
+                                                    'auteur' => null,
+                                                    'id_lieu' => 3,
+                                                    'domaine_ids' => ['11', '12'],
+                                                    'id_cat' => 23,
+                                                    'langue' => null,
+                                                    'titre' => 'Langue non spécifiée',
+                                                    'description' => '',
+                                                    'contenu' => 'test: http://monurl.fr.',
+                                                    'date_creation' => '2010-12-25'])]);
+
+
+
+    $this->postDispatch('/admin/ajax/force-https/', ['url' => urlencode('http://monurl.fr')
+                                                     ]);
+  }
+
+
+  /** @test */
+  public function shouldRedirect() {
+    $this->assertEquals('test: https://monurl.fr.',Class_Article::find(4)->getContenu());
+  }
+
+
+}
-- 
GitLab