--- /dev/null
+<%@page import="com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil"%>
+<% /**
+*Copyright Igor Barma, Alexandre Desoubeaux, Christian Martel, Eric Brun, Mathieu Amblard, Gwenael Gevet, Pierre Guillot, 2012
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Alexandre Lefevre, Marc Salvat 2014-2016
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Marc Salvat, Marc Suarez, Harifetra Ramamonjy 2017
+*
+*This file is part of the work and learning management system Pentila Nero.
+*
+*Pentila Nero is free software. You can redistribute it and/or modify since
+*you respect the terms of either (at least one of the both license) :
+*- under the terms of the GNU Affero General Public License as
+*published by the Free Software Foundation, either version 3 of the
+*License, or (at your option) any later version.
+*- the CeCILL-C as published by CeCILL-C; either version 1 of the
+*License, or any later version
+*- the GNU Lesser General Public License as published by the
+*Free Software Foundation, either version 3 of the license,
+*or (at your option) any later version.
+*
+*There are special exceptions to the terms and conditions of the
+*licenses as they are applied to this software. View the full text of
+*the exception in file LICENSE-PROJECT.txt in the directory of this software
+*distribution.
+*
+*Pentila Nero is distributed in the hope that it will be useful,
+*but WITHOUT ANY WARRANTY; without even the implied warranty of
+*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+*Licenses for more details.
+*
+*You should have received a copy of the GNU Affero General Public License
+*and the CeCILL-C and the GNU Lesser General Public License along with
+*Pentila Nero. If not, see :
+*<http://www.gnu.org/licenses/> and
+*<http://www.cecill.info/licences.fr.html>.
+*/ %>
+
+<%@page import="java.util.ArrayList"%>
+<%@page import="java.util.List"%>
+<%@page import="java.util.HashMap"%>
+<%@page import="java.util.Map"%>
+<%@page import="java.util.Date"%>
+<%@page import="java.text.SimpleDateFormat"%>
+<%@page import="java.io.BufferedReader"%>
+<%@page import="java.io.IOException"%>
+<%@page import="java.io.InputStream"%>
+<%@page import="java.io.InputStreamReader"%>
+<%@page import="java.net.URL"%>
+<%@page import="com.pentila.entSavoie.ENTDisplayUtil"%>
+<%@page import="com.liferay.portal.model.Organization"%>
+<%@page import="java.util.GregorianCalendar"%>
+<%@page import="java.util.Calendar"%>
+<%@page import="com.liferay.portal.model.Layout"%>
+<%@page import="com.liferay.portal.service.LayoutLocalServiceUtil"%>
+<%@page import="com.liferay.portal.service.LayoutLocalService"%>
+<%@page import="com.liferay.portal.model.UserGroup"%>
+<%@page import="com.liferay.portal.service.UserGroupLocalServiceUtil"%>
+<%@page import="com.pentila.entSavoie.portlets.statistics.PortletPropsValues"%>
+<%@page import="com.pentila.entSavoie.portlets.statistics.proxys.JsonEtabFactory"%>
+
+<%@ include file="./initAjax.jsp" %>
+
+<%
+
+ /* Chronometrage - debut */
+ Date start = new Date();
+
+
+ JSONObject ret = JSONFactoryUtil.createJSONObject();
+ JSONArray stats = JSONFactoryUtil.createJSONArray();
+
+ List<String> metadata = new ArrayList<String>();
+
+ /* Liste des URLs (complètes) qui seront appellés */
+ List<String> urls = new ArrayList<String>();
+
+ /* arguments de l'url */
+ Map<String,String> args = new HashMap<String, String>();
+
+ /* Profils nationaux */
+ Map<Long, String> profils = new HashMap<Long, String>();
+ profils.put(0L, "Tous");
+ profils.put(1L, "Elèves");
+ profils.put(2L, "Parents");
+ profils.put(3L, "Enseignants");
+ profils.put(4L, "Personnels de Direction");
+ profils.put(5L, "Personnel de vie scolaire");
+ profils.put(6L, "Personnel adminisrtatif");
+ profils.put(7L, "Personnel de la collectivité et autres profils");
+
+
+ /* segments spécifiques. Seront ajoutés à l'url de base pour former les urls complètes */
+ List<String> segments = new ArrayList<String>();
+ long companyId = themeDisplay.getCompanyId();
+ String url = ENTMainUtilsLocalServiceUtil.getPiwikApiUrl(companyId);
+ /* Ces arguments sont communs à toutes les requ^etes qu'on va faire */
+ args.put("token_auth",ENTMainUtilsLocalServiceUtil.getPiwikTokenAuth(companyId));
+ args.put("idSite",ENTMainUtilsLocalServiceUtil.getPiwikSiteId(companyId));
+ args.put("module","API");
+ args.put("format","json");
+ args.put("method","VisitsSummary.getVisits");
+
+
+ /* On regarde s'il faut générer plusieurs courbe */
+ String compareOn = renderRequest.getParameter("compareOn");
+ if(compareOn == null){
+ compareOn = "";
+ }
+
+ /* Récupération du groupage par période. Si null, on affiche les statistiques par jour, par défaut */
+ String period = ParamUtil.getString(renderRequest, "period");
+ if(period == null || "".equals(period)){
+ period = "day";
+ }
+ //System.out.println("ECHO period = " + period);
+ args.put("period",period);
+
+ /* Récupération des dates de début / fin voulus */
+ SimpleDateFormat classicDateFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+ Date startDate = null;
+ Date endDate = null;
+
+ String startDateString = renderRequest.getParameter("startDate");
+
+ if(startDateString == null || "".equals(startDateString)){
+
+ GregorianCalendar calendar = new java.util.GregorianCalendar();
+ calendar.setTime(new Date());
+ calendar.add(Calendar.MONTH, -1);
+ calendar.add(Calendar.DAY_OF_YEAR, +1);
+ startDate = calendar.getTime();
+
+ //System.out.println("setTime = " + startDate.getTime());
+ startDateString = classicDateFormat.format(startDate);
+ }
+ //System.out.println("ECHO startDateString = " + startDateString);
+ startDate = classicDateFormat.parse(startDateString);
+
+ String endDateString = renderRequest.getParameter("endDate");
+
+ if(endDateString == null || "".equals(endDateString)){
+ endDate = new Date();
+ endDateString = classicDateFormat.format(endDate);
+ }
+ //System.out.println("ECHO endDateString = " + endDateString);
+ endDate = classicDateFormat.parse(endDateString);
+
+ if(startDate != null && endDate != null){
+ //System.out.println("ECHO starTime = " + classicDateFormat.format(startDate) + " endDate = " + classicDateFormat.format(endDate));
+ args.put("date",classicDateFormat.format(startDate) + "," + classicDateFormat.format(endDate));
+ }
+
+ /* Récupération du/des profil(s) filtrés. Si aucun profil, on ajoute le profil 0 (tous) par défaut */
+ String profilsIdFull = ParamUtil.getString(renderRequest, "profilId");
+ String[] profilsIdString = profilsIdFull.split(",");
+ List<Long> profilsId = new ArrayList<Long>();
+
+ for(String s : profilsIdString){
+ try{
+ profilsId.add(Long.parseLong(s));
+ }
+ catch(Exception e) {}
+ }
+
+ /* Si aucun profil n'a été choisi, on prend tous par défaut */
+ if(profilsId.size() == 0){
+ profilsId.add(0L);
+ }
+
+ // liste des établissements
+ List<String> etabsId = new ArrayList<String>();
+
+ //Si le user n'est pas admin, on ne tiens pas compte des etabsId passés en paramètres
+// if(!JsonEtabFactory.isAdmin(user)){
+// //System.out.println("Le user n'est pas admin, on affiche que son etabRatachement");
+// Organization etabRattach = OrganizationFinderServiceUtil.getEtabRatachement(user);
+// etabsId.add(String.valueOf(etabRattach.getOrganizationId()));
+// }
+// else{
+ //System.out.println("Le user est admin, on tiens compte du filtre");
+ /* Récupération des établissements filtrés */
+ String etabsIdFull = ParamUtil.getString(renderRequest, "etabId");
+ String[] etabsIdArray = etabsIdFull.split(",");
+
+ for(String s : etabsIdArray){
+ if (!s.equals("")){
+ etabsId.add(s);
+ }
+ }
+// }
+
+ //System.out.println("ECHO etabsIdFull = " + etabsIdFull);
+ /*System.out.println("etabsId.size() = " + etabsId.size());
+ for(String s : etabsId){
+ System.out.print("#" + s + "#");
+ }
+ System.out.println("-------");*/
+
+
+ /* Récupération des services filtrés */
+ String servicesIdFull = ParamUtil.getString(renderRequest, "serviceId");
+ String[] servicesIdArray = servicesIdFull.split(",");
+
+ List<String> servicesId = new ArrayList<String>();
+ for(String s : servicesIdArray){
+ if (!s.equals("")){
+ servicesId.add(s);
+ }
+ }
+
+ //System.out.println("ECHO servicesIdFull = " + servicesIdFull);
+ //System.out.println("servicesId.size() = " + servicesId.size());
+ //for(String s : servicesId){
+ // System.out.print("#" + s + "#");
+ //}
+ //System.out.println("-------");
+
+ if(compareOn.equals("Profils")){
+
+ /* On va générer un segment par profil (=url) */
+ for(Long profilId : profilsId){
+
+ /* On donne le nom du profil à la série qui sera affichée */
+ metadata.add(profils.get(profilId));
+
+ String segment = "";
+
+ /* S'il y a un filtre par établissement, on en tiens compte */
+ for(String id : etabsId){
+ if(! "".equals(id) && ! "0".equals(id))
+ segment += "customVariableValue3=="+ id +",";
+ }
+
+ /* On supprime le dernier ',' */
+ if (!"".equals(segment) && segment.endsWith(",")){
+ segment = segment.substring(0, segment.length()-1);
+ segment += ";";
+ }
+
+ /* On ajout le filtre sur le profil unique (celui de la boucle actuelle) */
+ if(profilId != 0){
+ //System.out.println("ECHO profilId = " + profilId + " profils.get(profilId) = " + profils.get(profilId));
+ segment += "customVariableValue2=="+ profilId +";";
+ }
+
+ /* S'il y a un filtre par service, on en tiens compte */
+ for(String serviceId : servicesId){
+ if(! "".equals(serviceId) && ! "0".equals(serviceId)){
+ UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(Long.parseLong(serviceId));
+ if(userGroup != null){
+ List<Layout> applayouts = LayoutLocalServiceUtil.getLayouts(userGroup.getGroup().getGroupId(),true);
+
+ if(applayouts.size() > 0){
+ segment += "pageUrl=@"+ applayouts.iterator().next().getFriendlyURL() +",";
+ }
+ }
+ }
+ }
+
+ if (!"".equals(segment) && (segment.endsWith(",") || segment.endsWith(";"))){
+ /* On supprime le dernier ';' */
+ segment = segment.substring(0, segment.length()-1);
+ //segment += ";"; // on n'ajoute pas de ; parce que service est le dernier argument du segment
+ }
+
+ /* On ajoute le segment calculé à la liste pour la génération des urls plus tard */
+ segments.add(segment);
+ }
+
+ }
+
+ else if("Établissements".equals(compareOn)){
+
+ for(String etab : etabsId){
+
+ Organization principalOrg = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ List<Organization> listEtab = principalOrg.getSuborganizations();
+ String clgName ="";
+
+
+ if(! etab.equals("")){
+ Long etabid = Long.parseLong(etab);
+
+ for(Organization etabFor : listEtab){
+ if(etabFor.getPrimaryKey() == etabid){
+ clgName = ENTDisplayUtil.formatSCONETName(user, etabFor.getName());
+ }
+ }
+ }
+ else{
+ clgName = "Tous";
+ }
+
+ /* On donne le nom de l'établissement à la série qui sera affichée */
+ metadata.add(clgName);
+
+ String segment = "";
+
+ /* On ajout le filtre sur l'établissement unique (celui de la boucle actuelle) */
+ if(! "".equals(etab) && ! "0".equals(etab)){
+ segment += "customVariableValue3=="+ etab +";";
+ }
+
+ /* S'il y a un filtre par profil, on en tiens compte */
+ for(Long profilId : profilsId){
+ if(profilId != 0){
+ //System.out.println("ECHO profilId = " + profilId + " profilsIdFull = " + profils.get(profilId));
+ segment += "customVariableValue2=="+ profilId +",";
+ }
+ }
+
+ if(!"".equals(segment) && segment.endsWith(",")){
+ segment = segment.substring(0,segment.length()-1);
+ segment += ";";
+ }
+
+ /* S'il y a un filtre par service, on en tiens compte */
+ for(String serviceId : servicesId){
+ if(! "".equals(serviceId) && ! "0".equals(serviceId)){
+ UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(Long.parseLong(serviceId));
+ if(userGroup != null){
+ List<Layout> applayouts = LayoutLocalServiceUtil.getLayouts(userGroup.getGroup().getGroupId(),true);
+
+ if(applayouts.size() > 0){
+ segment += "pageUrl=@"+ applayouts.iterator().next().getFriendlyURL() +",";
+ }
+ }
+ }
+ }
+
+ /* On supprime le dernier ';' ou le dernier "," */
+ if (!"".equals(segment) && (segment.endsWith(",") || segment.endsWith(";"))){
+ segment = segment.substring(0, segment.length()-1);
+ //segment += ";"; // on n'ajoute pas de ; parce que service est le dernier argument du segment
+ }
+
+ /* On ajoute le segment calculé à la liste pour la génération des urls plus tard */
+ segments.add(segment);
+ }
+ }
+
+ else if("Services".equals(compareOn)){
+
+ for(String serviceId : servicesId){
+
+ /* On donne le nom du service à la série qui sera affichée */
+ String service = UserGroupLocalServiceUtil.getUserGroup(Long.parseLong(serviceId)).getName().substring(12);
+ metadata.add(service);
+
+ String segment = "";
+
+ /* S'il y a un filtre par établissement, on en tiens compte */
+ for(String id : etabsId){
+ if(! "".equals(id) && ! "0".equals(id))
+ segment += "customVariableValue3=="+ id +",";
+ }
+
+ if (!"".equals(segment) && segment.endsWith(",")){
+ segment = segment.substring(0, segment.length()-1);
+ segment += ";";
+ }
+
+ /* S'il y a un filtre par profil, on en tiens compte */
+ for(Long profilId : profilsId){
+ if(profilId != 0){
+ //System.out.println("ECHO profilId = " + profilId + " profilsIdFull = " + profils.get(profilId));
+ segment += "customVariableValue2=="+ profilId +",";
+ }
+ }
+
+ if(!"".equals(segment) && segment.endsWith(",")){
+ segment = segment.substring(0,segment.length()-1);
+ segment += ";";
+ }
+
+ /* On ajout le filtre sur le service unique (celui de la boucle actuelle) */
+ if(! "".equals(serviceId) && ! "0".equals(serviceId)){
+ UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(Long.parseLong(serviceId));
+ if(userGroup != null){
+ List<Layout> applayouts = LayoutLocalServiceUtil.getLayouts(userGroup.getGroup().getGroupId(),true);
+
+ if(applayouts.size() > 0){
+ segment += "pageUrl=@"+ applayouts.iterator().next().getFriendlyURL();
+ }
+ }
+ }
+
+ /* On ajoute le segment calculé à la liste pour la génération des urls plus tard */
+ segments.add(segment);
+ }
+ }
+
+ /* Cas où on ne compare rien, on ne fait qu'appliquer les filtres */
+ else{
+
+ //FIXME On l'appel comment la série dans ce cas ?
+ Organization principalOrg = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ List<Organization> listEtab = principalOrg.getSuborganizations();
+ String serieSansComparaison = " ";
+ if(etabsId.size() == 1){
+ Long etabid = Long.parseLong(etabsId.get(0));
+
+ for(Organization etabFor : listEtab){
+ if(etabFor.getPrimaryKey() == etabid){
+ serieSansComparaison = ENTDisplayUtil.formatSCONETName(user, etabFor.getName());
+ break;
+ }
+
+ }
+ }
+ metadata.add(serieSansComparaison);
+
+ String segment = "";
+
+ /* S'il y a un filtre par établissement, on en tiens compte */
+ for(String id : etabsId){
+ if(! "".equals(id) && ! "0".equals(id))
+ segment += "customVariableValue3=="+ id +",";
+ }
+
+ if (!"".equals(segment) && segment.endsWith(",")){
+ segment = segment.substring(0, segment.length()-1);
+ segment += ";";
+ }
+
+ /* S'il y a un filtre par profil, on en tiens compte */
+ for(Long profilId : profilsId){
+
+ if(profilId != 0){
+ //System.out.println("ECHO profilId = " + profilId + " profils.get(profilId) = " + profils.get(profilId));
+ segment += "customVariableValue2=="+ profilId +",";
+ }
+ }
+
+ if(segment.endsWith(",")){
+ segment = segment.substring(0,segment.length()-1);
+ segment += ";";
+ }
+
+ /* S'il y a un filtre par service, on en tiens compte */
+ for(String serviceId : servicesId){
+ if(! "".equals(serviceId) && ! "0".equals(serviceId)){
+ UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(Long.parseLong(serviceId));
+ if(userGroup != null){
+ List<Layout> applayouts = LayoutLocalServiceUtil.getLayouts(userGroup.getGroup().getGroupId(),true);
+
+ if(applayouts.size() > 0){
+ segment += "pageUrl=@"+ applayouts.iterator().next().getFriendlyURL() +",";
+ }
+ }
+ }
+ }
+
+ if (!"".equals(segment) && (segment.endsWith(",") || segment.endsWith(";"))){
+ /* On supprime le dernier ';' */
+ segment = segment.substring(0, segment.length()-1);
+ //segment += ";"; // on n'ajoute pas de ; parce que service est le dernier argument du segment
+ }
+
+ segments.add(segment);
+
+ }
+
+ /* On parcours tous les segments calculés précédement pour générer les URLs à appeller */
+ for(String segment : segments){
+
+ String specificUrl = url;
+
+ for(String s : args.keySet()){
+ specificUrl += s + "=" + args.get(s) + "&";
+ }
+ specificUrl += "segment=" + segment;
+
+ urls.add(specificUrl);
+ }
+
+ Date end = new Date();
+ long duree = end.getTime() - start.getTime();
+
+
+ Map<String, List<Object>> data = new HashMap<String, List<Object>>();
+
+ int cpt = 0;
+
+ /* Pour chaque URL généré, on appel l'API, et on range les données dans le map "data" */
+ for(String specificUrl : urls){
+
+ if(specificUrl.endsWith("&")){
+ /* On supprime le dernier '&' */
+ specificUrl = specificUrl.substring(0, specificUrl.length()-1);
+ }
+
+
+ InputStream is = new URL(specificUrl).openStream();
+ JSONObject result;
+
+ try {
+ /* récupération du json depuis piwik */
+ BufferedReader reader = new BufferedReader(new InputStreamReader(is));
+ StringBuilder sb = new StringBuilder();
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line + "\n");
+ }
+ String jsonText = sb.toString();
+ JSONObject obj = JSONFactoryUtil.createJSONObject(jsonText);
+
+ /* On récupère les clé (dates) et on les tri dans l'ordre croissant */
+ List<String> keys = new ArrayList<String>();
+ for (java.util.Iterator<String> iterator = obj.keys(); iterator.hasNext();) {
+ keys.add(iterator.next());
+ }
+ java.util.Collections.sort(keys);
+
+ /* peuplement du JSONArray de sortie à partir des clés triés */
+ for (String cle : keys) {
+
+ Integer val = obj.getInt(cle);
+
+ /* On n'ajoute pas les éventuels messages d'erreur */
+ if("message".equals(cle) || "result".equals(cle) || "error".equals(val)){
+ //System.out.println("skip entry ... " + cle + ":" + val);
+ continue;
+ }
+
+ if(! data.containsKey(cle)){
+ List<Object> l = new ArrayList<Object>();
+ data.put(cle,l);
+ }
+ data.get(cle).add(metadata.get(cpt) + "!" + val);
+ }
+ }
+ finally {
+ is.close();
+ }
+ cpt++;
+ }
+
+ /* Toutes les données sont en place dans le map. On génère les JSON-résultat */
+
+ List<String> keysSorted = new ArrayList<String>(data.keySet());
+ java.util.Collections.sort(keysSorted);
+
+ JSONArray metadata2 = JSONFactoryUtil.createJSONArray();
+ metadata2.put("date");
+
+ for(String meta : metadata){
+ metadata2.put(meta);
+ }
+
+ JSONArray dataJSON = JSONFactoryUtil.createJSONArray();
+
+ for(String key : keysSorted){
+ JSONObject stat = JSONFactoryUtil.createJSONObject();
+ stat.put("date", key);
+
+ for(Object o : data.get(key)){
+
+ String val = o.toString();
+ String debut = val.substring(0, val.lastIndexOf("!"));
+ String fin = val.substring(val.lastIndexOf("!")+1, val.length());
+
+ stat.put(debut, fin);
+
+ }
+ dataJSON.put(stat);
+ }
+
+ JSONObject wrap = JSONFactoryUtil.createJSONObject();
+ wrap.put("metadata", metadata2);
+ wrap.put("data", dataJSON);
+ stats.put(wrap);
+
+ ret.put("stats", stats);
+
+%>
+<%= ret.toString() %>