'')); $_aReq['olindoteTools'] = json_encode(array('id'=> self::ot_checkUserId(), 'origine'=>$_type.'|'.$_plugin.'|'.$_cVersion, 'class'=>$_class, 'plugins'=> $_plugins)); log::add('olindoteTools','debug','[ot_sendInfoToOlindote()] data send='.print_r($_aReq,true)); $_sUrl = ($debug)?OLINDOTE_USER_INFO_URL.'?debug':OLINDOTE_USER_INFO_URL; self::network_sendRequestByCurl('olindoteTools', $_sUrl, $_aReq); } } /* ------------------------------------------------------------------------------------------------------------- */ /* ----- ************************** Gestion des fonctions "d'archivage du plugin" ****************************** */ /** * Création du backup * @param String $_plugin nom du plugin */ public static function backup_createBackup($_plugin='', $_aPath=array(), $_lastDelete=true) { if ($_plugin=='') return false; /*$_backupDirectory = config::byKey('backup::directory','olindoteTools',''); if ($_backupDirectory!='') { self::$_PATH_BACKUP = $_backupDirectory; } else { self::$_PATH_BACKUP = cleanPath(dirname(__FILE__).self::$_PATH_BACKUP); config::save('backup::directory', self::$_PATH_BACKUP, $_plugin); }*/ // crée le répertoire // if (!self::checkAndCreateDirectory($_plugin, OLINDOTE_DIR_BACKUP)) { log::add($_plugin.'_backup', 'warning', '[olindoteTools::backup_createBackup()] can NOT create backup directory !'); return false; } // supprimer les fichiers temporaires dans le répertoire (si besoin) self::backup_deleteTmpPath($_plugin, $_aPath=array()); // suppression de l'ancien fichier (correspond à l'archive X-2) // if ($_lastDelete) { $_lastFN = config::byKey('backup::lastFile',$_plugin,''); if ($_lastFN != '') { if (file_exists(OLINDOTE_DIR_BACKUP.'/'.$_lastFN)) { unlink(OLINDOTE_DIR_BACKUP.'/'.$_lastFN); log::add($_plugin.'_backup', 'debug', '[olindoteTools::backup_createBackup()] oldest file are delete ('.OLINDOTE_DIR_BACKUP.'/'.$_lastFN.')'); } } config::save('backup::lastFile', '', $_plugin); } // création du fichier temporaire // $_newFN = self::backup_getFileName($_plugin); $_zipDest = OLINDOTE_DIR_BACKUP.'/'.$_newFN.'.zip'; $_repSource = getRootPath().'/plugins/'.$_plugin; //cleanPath(dirname(__FILE__) .'/../../../../plugins/'.$_plugin); if (file_exists($_zipDest)) { unlink($_zipDest); log::add($_plugin.'_backup', 'debug', '[olindoteTools::backup_createBackup()] new file name already exist, delete it ('.$_zipDest.')'); } if (!create_zip($_repSource, $_zipDest)) { log::add($_plugin.'_backup', 'warning', '[olindoteTools::backup_createBackup()] ERROR during create zip file (source="'.$_repSource.'" / zip="'.$_zipDest.'")'); return false; } log::add($_plugin.'_backup', 'debug', '[olindoteTools::backup_createBackup()] Plugin directory ('.$_repSource.') is archived on zip file ('.$_zipDest.')'); config::save('backup::lastFile', config::byKey('backup::currentFile',$_plugin,''), $_plugin); config::save('backup::currentFile', $_newFN, $_plugin); return true; } /** * Retourne le nom du fichier d'archive * -- plugin_versionPlugin_versionJeedom_dateArchive * @param String $_plugin nom du plugin */ public static function backup_getFileName($_plugin='') { if ($_plugin=='') return false; return $_plugin.'_'.str_replace('.','-',self::getInfoOnInfoJson($_plugin,'_oT_pluginVersion')).'_'.str_replace('.','-',jeedom::version()).'_'.date('YmdHis'); } /** * Suppression des fichiers temporaires (s'il y a) * @param String $_plugin nom du plugin */ public static function backup_deleteTmpPath($_plugin='', $_aPath=array()) { //$_pathPlugin = cleanPath(dirname(__FILE__) .'/../../../../plugins/'.$_plugin.'/'); $_pathPlugin = getRootPath().'/plugins/'.$_plugin.'/'; if (count($_aPath)>0) { for($i=0;$i 0) { foreach ($_aFiles as $_f) unlink($_f); log::add($_plugin, 'debug', '[olindoteTools::backup_deleteTmpPath()] nb file = "'.$_nbTmp.'" on "'.$_pathDir.'"'); } else log::add($_plugin, 'debug', '[olindoteTools::backup_deleteTmpPath()] no files on this directory: "'.$_pathDir.'"'); } } } } /** * Initialisation des données pour la fonction backup * @param String $_plugin nom du plugin */ public static function backup_init($_plugin='') { if ($_plugin=='') return false; config::save('backup::directory', '', $_plugin); config::save('backup::currentFile', '', $_plugin); config::save('backup::lastFile', '', $_plugin); } /* ------------------------------------------------------------------------------------------------ */ /* ----- ************************** Gestion de la variable "Version" ****************************** */ /** * Initialise les informations et sauvegarde (retourne le tableau, au besoin) * @param String $_plugin nom du plugin * @param boolean $_save définie s'il faut sauvegarder en table de config */ public static function version_setValue($_plugin='', $_save=true) { if ($_plugin=='') return false; $_versionDefault = '0.0.1'; $_aVersion = config::byKey('olindote::version',$_plugin,0); if (!is_array($_aVersion)) $_aVersion = array(); $_aVersion['lastVersion'] = (isset($_aVersion['curVersion']))?$_aVersion['curVersion']:false; $_aVersion['lastVersionDate'] = (isset($_aVersion['curVersionDate']))?$_aVersion['curVersionDate']:false; $_aVersion['lastVJeedom'] = jeedom::version(); $_versionInJson = self::getInfoOnInfoJson($_plugin,'_oT_pluginVersion'); $_aVersion['curVersion'] = ($_versionInJson===false)?$_versionDefault:$_versionInJson; $_aVersion['curVersionDate'] = date('Y-m-d H:i:s'); if ($_save) config::save('olindote::version', $_aVersion, $_plugin); } /** * Récupère les informations depuis la config jeedom * @param String $_plugin nom du plugin */ public static function version_getPluginInfo($_plugin='') { $_aV = array(); if ($_plugin=='') { return false; } $_aV = config::byKey('olindote::version',$_plugin,'?'); $_aVersionReturn['curVersion'] = (is_array($_aV)&&(isset($_aV['curVersion'])))?$_aV['curVersion']:$_aV; $_aVersionReturn['curVersionDate'] = (is_array($_aV)&&(isset($_aV['curVersionDate'])))?$_aV['curVersionDate']:false; $_aVersionReturn['lastVersion'] = (is_array($_aV)&&(isset($_aV['lastVersion'])))?$_aV['lastVersion']:false; $_aVersionReturn['lastVersionDate'] = (is_array($_aV)&&(isset($_aV['lastVersionDate'])))?$_aV['lastVersionDate']:false; $_aVersionReturn['lastVJeedom'] = (is_array($_aV)&&(isset($_aV['lastVJeedom'])))?$_aV['lastVJeedom']:false; return $_aVersionReturn; } /* ---------------------------------------------------------------------------------------------- */ /* ----- ************************** Gestion des échanges "Réseaux" ****************************** */ /** * Met à jour l'état de la santé du réseau pour l'équipement/commande concernée * @param array $_aStat tableau avec l'état et la date : 'date'=>'statut' * @param object $_obj eqlogic ou cmd, * @param string $_plugin nom du plugin */ public static function network_setHealth($_aStat, $_obj) { $_plugin = self::getObjName($_obj); if ($_plugin=='') return false; if ((is_array($_aStat)) && (count($_aStat)>0)) { $_healthNetwork = $_obj->getConfiguration('healthNetwork',false); // TODO: A SUPPRIER à la prochaine version // if ($_healthNetwork===false) { $_healthNetwork = $_obj->getConfiguration('oT::Network::health',array()); } else { $_obj->setConfiguration('healthNetwork', false); } // TODO: trouver le moyen de supprimer ce paramètre de "configuration" // $_nbLast = config::byKey('health::network::nbLast', $_plugin ,10); $_healthNetwork = (count($_healthNetwork)>=$_nbLast)?array_slice($_healthNetwork,0,($_nbLast-1)):$_healthNetwork; array_unshift($_healthNetwork, json_encode($_aStat)); if (current($_aStat)=='X') { self::network_setStatut($_obj,false); } else { self::network_setStatut($_obj,true); if (substr(strtolower(get_class($_obj)),-3)!='cmd') $_obj->setStatus(array('lastCommunication' => date('Y-m-d H:i:s'), 'timeout' => 0)); } log::add($_plugin, 'debug', '['.((isset($_obj->_whatLog))?$_obj->_whatLog:'').'|'.$_obj->getName().'('.$_obj->getId().')] network_setHealth()._healthNetwork='.print_r($_healthNetwork,true)); // sauvegarde des informations // $_obj->_isSimpleSave = true; $_obj->setConfiguration('oT::Network::health', $_healthNetwork); $_obj->save(); return true; } log::add($_plugin, 'debug', '['.((isset($_obj->_whatLog))?$_obj->_whatLog:'').'|'.$_obj->getName().'('.$_obj->getId().')] network_setHealth(): ERROR: data information is not an array'); return false; } /** * Retourne l'état du réseau à afficher sur la page santé */ public static function network_setArrayHealthForHealthPage($_obj) { $_plugin = self::getObjName($_obj); if ($_plugin=='') return false; if ($_obj->getIsEnable()) { $_iconOK = ""; $_iconKO = ""; $_nbError=0; $_healthNetwork = $_obj->getConfiguration('healthNetwork',false); // TODO: A SUPPRIER à la prochaine version // if ($_healthNetwork===false) { $_healthNetwork = $_obj->getConfiguration('oT::Network::health',array()); } $_resEqL['state'] = true; $_resEqL['test'] = __('Etat réseau de',__FILE__).' : "'.$_obj->getName().'"'; $_resEqL['result'] = ''; $_resEqL['advice'] = ''; foreach($_healthNetwork as $_aState) { $_aStateJson = json_decode($_aState); if (count((array)$_aStateJson) > 0) { foreach($_aStateJson as $_k => $_v) { if($_v=='X') { $_resEqL['state'] = false; $_nbError++; log::add($_plugin, 'debug', 'Bison Error : ' . $_nbError); } $_resEqL['result'] = $_resEqL['result'].''.(($_v=='o')?$_iconOK:$_iconKO).' '; } } } if ($_resEqL['result'] == '') return false; if (!$_resEqL['state']) { $_resEqL['advice'] = __('Au cours des ',__FILE__).config::byKey('health::network::nbLast', $_plugin, 10).__(' derniers accès, ',__FILE__).$_nbError.__(' sont en erreur.',__FILE__); } return $_resEqL; } return false; } /** * Retourne le résultat d'une requête CURL (error/info/data) */ public static function network_sendRequestByCurl($_plugin='', $_sURL='', $_aData=null, $_timeOut=10) { if ((is_null($_sURL))||($_sURL=='')||(empty($_sURL))) { return false; } $_ch = curl_init(); $_return['fError'] = ""; curl_setopt($_ch, CURLOPT_HEADER, false); curl_setopt($_ch, CURLINFO_HEADER_OUT, true); curl_setopt($_ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($_ch, CURLOPT_URL, $_sURL); curl_setopt($_ch, CURLOPT_TIMEOUT, (($_timeOut!=null)?$_timeOut:10)); if (substr($_sURL,0,6)=='https:') { curl_setopt($_ch, CURLOPT_SSL_VERIFYPEER, false); } if ((is_array($_aData))&&(count($_aData)>0)) { curl_setopt($_ch, CURLOPT_POST, 1); curl_setopt($_ch, CURLOPT_POSTFIELDS, $_aData); } $_return['fData'] = curl_exec($_ch); $_return['fInfo'] = curl_getinfo($_ch); if ((isset($_fInfo['http_code']))&&($_fInfo['http_code']==0)) { $_return['fError'] = curl_error($_ch); } curl_close($_ch); log::add($_plugin,'debug','[olindoteTools::network_sendRequestByCurl()] _return='.print_r($_return,true)); return $_return; } /** * Enregistre le dernier état réseau */ public static function network_setStatut($_obj, $_value) { $_obj->_isSimpleSave = true; $_obj->setConfiguration('oT::Network::statut', $_value); if ($_value==false) { if (empty($_obj->getConfiguration('oT::Network::healthLastDate',''))) $_obj->setConfiguration('oT::Network::healthLastDate',date('Y-m-d H:i:s')); } else { $_obj->setConfiguration('oT::Network::healthLastDate',''); } $_obj->save(); } /** * Récupère le dernier état réseau */ public static function network_getStatut($_obj) { return $_obj->getConfiguration('oT::Network::statut', false); } /** * Récupère la date du dernier état réseau */ public static function network_getLastDateStatut($_obj) { if (!is_object($_obj)) return ''; return $_obj->getConfiguration('oT::Network::healthLastDate',''); } /* -------------------------------------------------------------------------------------------------------------------------- */ /* ----- ************************** HTML // Gestion d'affichage des zones communes dans Jeedom ****************************** */ /** * Définie la zone des boutons de configuration * @param array $_aMenus tableau listant les menus autorisés */ public static function eqlogicHtml_zoneGestion($_plugin, $_aMenus) { $_sHtml = ' '.__("Gestion",__FILE__).'
'; $_sOneMenu = "

%TEXT%
"; if (count($_aMenus)>0) { foreach ($_aMenus as $_menu) { if (is_array($_menu)) { if (isset($_menu['id']) && isset($_menu['class']) && isset($_menu['color']) && isset($_menu['txt'])) { $_sHtml .= str_replace(array('%EVENT-ACTION%','%PICTO-CLASS%','%PICTO-COLOR%','%TEXT%'), array($_menu['id'],$_menu['class'],$_menu['color'],$_menu['txt']), $_sOneMenu); } else { log::add($_plugin, 'warning', '[olindoteTools::eqlogicHtml_zoneGestion()] ERROR: param menu is not good ; _menu='.print_r($_menu,true)); } } else { switch($_menu) { case "add": $_sHtml .= str_replace(array('%EVENT-ACTION%','%PICTO-CLASS%','%PICTO-COLOR%','%TEXT%'), array('data-action="add"','fa fa-plus-circle','var(--logo-primary-color)',__('Ajouter',__FILE__)), $_sOneMenu); break; case "config": $_sHtml .= str_replace(array('%EVENT-ACTION%','%PICTO-CLASS%','%PICTO-COLOR%','%TEXT%'), array('data-action="gotoPluginConf"','fa fa-wrench','var(--logo-secondary-color)',__('Configuration',__FILE__)), $_sOneMenu); break; } } } } return $_sHtml.'
'; } /** * Définie la zone d'affichage des eqLogic * @param array $_aEqLogics tableau des eqLogic * @param array $__titleTable nom du tableau */ public static function eqlogicHtml_zoneEqlogicList($_plugin, $_titleTable, $_aEqLogics, $_showTableList=array('btn'=>false,'tab'=>false,'search'=>true,'btnTabJeedom'=>false), $_hideObj=array(), $_txtNoData='') { $_sHtml = ' '.$_titleTable.''; $_sHtmlTableItem = ''; $opacity = ''; if ((!is_array($_showTableList))&&($_showTableList)) $_showTableList = array('btn'=>true,'tab'=>true,'search'=>true); $_hasColumnFromPlugin = false; if (isset($_showTableList['search'])&&($_showTableList['search'])) { //$_sHtml .= ""; $_sHtml .= "
"; if (isset($_showTableList['btnTabJeedom'])&&($_showTableList['btnTabJeedom'])) { $_sHtml .= ""; } if (isset($_showTableList['btn'])&&($_showTableList['btn'])) { $_sHtml .= ""; } $_sHtml .= "
"; } $_sHtml .= "
"; if (count($_aEqLogics) == 0) { $_txtNoData = ($_txtNoData!='')?$_txtNoData:__('Vous n\'avez pas d\'équipement configuré ('.$_titleTable.'). Cliquez sur "Ajouter" pour créer votre 1er équipement.',__FILE__); $_sHtml .= "
"; // fin du eqLogicThumbnailContainer en cas de "no data" (le alerte ne doit pas être dans le div) // $_sHtml .= "
".$_txtNoData."
"; } else { $_sHtml .= ""; $_sHtml .= ""; if (isset($_showTableList['tab'])&&($_showTableList['tab'])) { $_sHtmlTable = ""; $_sHtml .= str_replace('%TABLE_LIST%',$_sHtmlTableItem,$_sHtmlTable); } $_sHtml .= ""; // fin du eqLogicThumbnailContainer en cas de "data" // } if (isset($_showTableList['btn'])&&($_showTableList['btn'])) { $_eqLViewType = config::byKey('olindote::eqLogic::viewType',$_plugin,'Icons'); $_sHtml .= ""; } return $_sHtml; } /** * Définie la liste des menus d'action à afficher * @param array $_aMenus tableau listant les menus autorisés */ public static function eqlogicHtml_writeMenuAction($_aMenus) { $_sHtml = '
'; if (count($_aMenus)>0) { foreach ($_aMenus as $_menu) { if (is_array($_menu)) { $_sHtml .= ' '.$_menu['name'].''; break; } else { switch($_menu) { case "save": $_sHtml .= ' {{Sauvegarder}}'; break; case "remove": $_sHtml .= ' {{Supprimer}}'; break; case "copy": $_sHtml .= ' {{Dupliquer}}'; break; case "configure": $_sHtml .= ' {{Configuration avancée}}'; break; } } } } return $_sHtml."
"; } /** * Définie la liste du menu de gauche * @param array $_eqLogics tableau listant les eqLogics * // ATTENTION : zone condannée en Jeedom V4 (maintenue en V3) */ public static function eqlogicHtml_zoneLeftMenu($_eqLogics, $_showAdd=true, $_showSearch=true, $_hideObj=array()) { $_sHtml = ''; if (!self::jeedom_isCompatibleVersion('3.3.28')) { $_sHtml .= '
'; $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= '
'; } return $_sHtml; } /** * Retourne le nom du paramètre en cache pour le contenu du Widget */ public static function eqlogicHtml_getWidgetCacheName($_version, $_obj) { $_objId = (is_object($_obj))?$_obj->getId():'Z9Z'; $user_id = ''; if (isset($_SESSION) && isset($_SESSION['user']) && is_object($_SESSION['user'])) { $user_id = $_SESSION['user']->getId(); } return 'widgetHtml'.$_objId.$_version.$user_id; } /** * Définie la zone des onglets sur la page équipement */ public static function eqlogicHtml_tabList($_aTabList) { $_aDefaultTab = array( '#eqlogictab'=>array('h'=>'#eqlogictab','ctl'=>'home','i'=>'fa fa-terminal','n'=>__('Equipement',__FILE__),'c'=>'oT_eqTabName'), '#paramtab'=>array('h'=>'#paramtab','ctl'=>'profile','i'=>'fas fa-check-square','n'=>__('Paramètres',__FILE__),'c'=>'') ); $_sHtml = ''; $_sHtml .= ''; return $_sHtml; } /** * Affiche les données propres à JEEDOM page équipement (nom, catégorie, ...) */ public static function eqlogicHtml_zoneEquipement($_hideField=array(),$_specificHtml='') { $_sHtml = ''; $_sHtml .= '
'; $_sHtml .= '
'; $_sHtml .= ' '.self::html_setIcone('fa fa-tachometer').' '.__('Equipement Jeedom',__FILE__).''; $_sHtml .= ' '; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= '
'; if (!in_array('object',$_hideField)) { $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= '
'; } $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; $_sHtml .= __('Activé',__FILE__).' :  '; if (!in_array('isVisible',$_hideField)) { $_sHtml .= __('Visible',__FILE__).' : '; } $_sHtml .= '
'; $_sHtml .= '
'; if (!in_array('category',$_hideField)) { $_sHtml .= '
'; $_sHtml .= ' '; $_sHtml .= '
'; foreach (jeedom::getConfiguration('eqLogic:category') as $key => $value) { $_sHtml .= ' '; } $_sHtml .= '
'; $_sHtml .= '
'; } if (strlen($_specificHtml)>0) { $_sHtml .= $_specificHtml; } $_sHtml .= '
'; $_sHtml .= '
'; return $_sHtml; } /** * Retourne la class icone en fonction de la version de Jeedom * // Impossé suite au passage en V4 Jeedom > pourra être supprimé à terme */ public static function html_setIcone($_class,$_classOnly=false) { $_html = ""; switch ($_class) { case "fa fa-refresh" : $_class=(self::jeedom_isCompatibleVersion('4.0.00'))?'fa fa-sync':'fa fa-refresh'; break; case "fa fa-pencil-square-o" : $_class=(self::jeedom_isCompatibleVersion('4.0.00'))?'fas fa-pencil-alt':'fa fa-pencil-square-o'; break; case "fa fa-tachometer" : $_class=(self::jeedom_isCompatibleVersion('4.0.00'))?'fas fa-tachometer-alt':'fa fa-tachometer'; break; } return ($_classOnly)?$_class:str_replace('%%CLASS%%',$_class,$_html); } /* ----- ************************** HTML // Ajout des zones d'info sur la page configuration ****************************** */ /** * Tableaux de synthèse de la page Configuration */ public static function pluginInfo_writeHtml($_plugin='') { $debug=true; $_sHtml = ""; return $_sHtml; } /* ----- ************************** HTML // Gestion des icones d'aide ou d'info ****************************** */ /** * Retourne le zone html correspondant à la partie "help" * @param String $_txt texte à afficher * @param String $_icone icone à afficher */ public static function help_writeHtmlIcone($_txt, $_sup=true, $_icone='', $_txtStyle='') { if (is_array($_txt)) $_txt = implode('
',$_txt); if ($_icone=='') $_icone = ""; if ($_txtStyle!='') $_txtStyle = "style='".$_txtStyle."'"; $_sHtml = "".((!$_sup)?$_icone:"".$_icone."")."".$_txt.""; return $_sHtml; } /** * Retourne le zone html correspondant à la partie CSS du "help" */ public static function help_writeHtmlCss() { $_sHtml = ""; } /* ----- ************************** Calcul Gestion des listes ****************************** */ /** * Récupère les paramètres/valeurs d'une liste * @param String $_plugin * @param String $_listName * @param String $_activeOnly */ public static function getListValues($_plugin='', $_listName='', $_activeOnly='1') { $_plugin = ($_plugin=='')?'olindoteTools':$_plugin; if ($_listName=='') { log::add($_plugin, 'debug', '[olindoteTools::getListValues()] _listName ('.$_listName.') is empty // STOP'); return false; } if (!class_exists($_plugin.'Tools')) { log::add($_plugin, 'debug', '[olindoteTools::getListValues()] this class ('.$_plugin.'Tools) does not exist ! // STOP'); return false; } $_return = array(); eval('$_return = (isset('.$_plugin.'Tools'.'::$'.$_listName.'))?'.$_plugin.'Tools'.'::$'.$_listName.':array();'); if (($_activeOnly==1)&&(count($_return)>0)) { for ($i=0; $i$_l2[0],'n'=>$_l2[1]); } } if (count($_listValues)>0) { for ($i=0; $i".$_listValues[$i]['n'].""; } } return $_return; } /* ----- ************************** FILE // Action sur des fichiers ****************************** */ /** * Retourne une liste de fichier */ public static function file_getList($_plugin='olindoteTools',$_dir='.',$_excludeDir=true,$_excludeExt=array()) { if (!file_exists($_dir)) { log::add($_plugin, 'warning', '[olindoteTools::file_getList()] directory not exist ('.$_dir.')'); return false; } $_aFiles = scandir($_dir); if (($k1=array_search('.',$_aFiles))!==false) unset($_aFiles[$k1]); if (($k2=array_search('..',$_aFiles))!==false) unset($_aFiles[$k2]); sort($_aFiles); if ($_excludeDir) { for ($i=0;$i$_wAsk)||($height > $_hAsk)) { if ($width > $height) { $r = $height/$width; $newwidth = $_wAsk; $newheight = ceil($_hAsk*$r); } else { $r = $width/$height; $newwidth = ceil($_wAsk*$r); $newheight = $_hAsk; } log::add($_plugin, 'info', '[olindoteTools::file_resizePicture()] file w='.$width.',h='.$height.' - ask w='.$_wAsk.',h='.$_hAsk.' - new w='.$newwidth.',h='.$newheight); } else { $newwidth = $width; $newheight = $height; } $_extFile = strtolower(strrchr($_file, '.')); if ($_extFile == '.png') { $srcPic = imagecreatefrompng($_file); } else if (in_array($_extFile, array('.jpg','.jpeg'))) { $srcPic = imagecreatefromjpeg($_file); } else { log::add($_plugin, 'warning', '[olindoteTools::file_resizePicture()] picture with not a good extension (found='.$_extFile.' - allow=.jpg, .jpeg, .png)'); return $_return; } $dstPic = imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($dstPic,$srcPic,0,0,0,0,$newwidth,$newheight,$width,$height); if ($_extFile == '.png') { $_return = imagepng($dstPic, $_file); } else if (in_array($_extFile, array('.jpg','.jpeg'))) { $_return = imagejpeg($dstPic, $_file); } return $_return; } /** * Supprime les caractères spéciaux d'un string */ static function file_removeSpecialString($_t) { $utf8 = array( '/[áàâãªä]/u'=>'a', '/[ÁÀÂÃÄ]/u'=>'A', '/[ÍÌÎÏ]/u'=>'I', '/[íìîï]/u'=>'i', '/[éèêë]/u'=>'e', '/[ÉÈÊË]/u'=>'E', '/[óòôõºö]/u'=>'o', '/[ÓÒÔÕÖ]/u'=>'O', '/[úùûü]/u'=>'u', '/[ÚÙÛÜ]/u'=>'U', '/ç/'=>'c', '/Ç/'=>'C', '/ñ/'=>'n', '/Ñ/'=>'N', '/\[\]/u'=>'', '/[«»]/u'=>'_', '/ /'=>'_' ); /* '//'=>'-', */ return preg_replace(array_keys($utf8), array_values($utf8), $_t); } /* ----- ************************** Calcul sur les dates ****************************** */ /** * Convertie la date dans un format */ public static function convertDate($_d, $_type) { if ($_d!='') { switch($_type) { case "DUREE2D": // "Seconde" > "day" $_d = intval($_d/(24*3600)); break; case "DUREE2HMS": // "Seconde" > "hh:mm:ss" $_tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $_d = date('d',$_d); date_default_timezone_set($_tz); break; case "TS2FC": // "TS" > "YYYY-MM-DDThh:mm:ss" $_d = date('Y-m-d\TH:i:s',$_d); break; case "TS2ICS": // "TS GM" > "YYYYMMDDThhmmssZ" $_d = date('Ymd\THis\Z',$_d); break; case "ONLYNUMBER": // A SUPPRIMER !!! // case "HUMANCLEARED": // "Y-m-d H:i:s" > "YmdHis" $_d = str_replace('-','',str_replace(':','',str_replace(' ','',$_d))); break; case "HUMAN2TS": // "Y-m-d H:i:s" > "TS" if ($_d==0) $_d = time(); else { list($_ad, $_ah) = explode(' ',$_d); list($_dy, $_dm, $_dd) = explode('-',$_ad); list($_hh, $_hi, $_hs) = explode(':',$_ah); $_d = mktime($_hh,$_hi,$_hs,$_dm,$_dd,$_dy); } break; case "DAYJEEDOM": // "Ymd" > "Y-m-d" $_d = substr($_d,0,4).'-'.substr($_d,-4,2).'-'.substr($_d,-2); break; case "DAYHUMAN": // "Y-m-d 00:00:00" > "j F Y" list($_dy, $_dm, $_dd) = explode('-',str_replace(' 00:00:00','',$_d)); $_d = date('j F Y', mktime('0','0','0',$_dm,$_dd,$_dy)); // date_fr() break; case "TODAY": $_dEng = (config::byKey('language', 'core', 'fr_FR')=='fr_FR')?date('j F Y (\SW)'):date('j F Y (\WW)'); $_d = date_fr($_dEng); break; } } return $_d; } /** * Définie la date en fonction d'une date actuelle et d'un temps en plus. * @param String $_refreshP période à ajouter * @param String $_dt1 date/time initiale * @param boolean $_isSpecificTest cas particulier */ /* public static function getDateNext($_refreshP, $_dt1='', $_isSpecificTest=false) { $_next = 0; $_dt = ($_dt1=='')?time():$_dt1; if ($_isSpecificTest) { if ($_refreshP == '30') { if (($_m=date('i',$_dt)) < 30) $_next = $_dt+((30-$_m)*60); else $_next = $_dt+((60-$_m)*60); } elseif ($_refreshP == '1440') { $_next = mktime('00','00','00', $_dt) + (1440*60); } } if ($_next==0) { $_refreshP = $_refreshP/60; $_h=$_refreshP-(date('H',$_dt)%$_refreshP); // (modulo=nb heure passée après la précédente synchro); $_next= $_dt + ($_h*60*60) - (date('i',$_dt)*60); } log::add($_plugin, 'debug', '[olindoteTools::getDateNext()] _next='.$_next); return $_next; }*/ /* ----- ************************** Gestion fonction "ajax" ****************************** */ /** * Traite les demandes Ajax des plugins liées à la class olindoteTools */ public static function execAjaxRequest($_plugin, $_action) { log::add($_plugin,'debug','[AJAX] execAjaxRequest(): action='.$_action); $_return = array('type'=>'na', 'value'=>''); // méthode = sauvegarde le nom de la commande // if ($_action == 'oT_saveSendInfo') { config::save('sendInfo::allow', init('sendInfo_allow'), 'olindoteTools'); $_return = array('type'=>'success', 'value'=>''); } // méthode = sauvegarde le format de vue sur une page équipement // if ($_action == 'oT_saveEqLogicViewType') { config::save('olindote::eqLogic::viewType', init('eqLogicViewType'), $_plugin); $_return = array('type'=>'success', 'value'=>''); } log::add($_plugin,'debug','[AJAX] execAjaxRequest(): _return='.print_r($_return,true)); return $_return; } /* ----- ************************** Fonctions génériques ****************************** */ /** * Définie si la version courante est compatible avec celle demandée */ public static function jeedom_isCompatibleVersion($_v) { $_aV = explode('.',$_v); $_aJeedomV = explode('.',jeedom::version()); if ($_aJeedomV[2] < 10) $_aJeedomV[2] = '0'.$_aJeedomV[2]; if (implode('',$_aJeedomV) >= implode('',$_aV)) return true; else return false; } /** * Récupère un paramètre/valeur dans le fichier Json du plugin (jeedom) * @param String $_plugin nom du plugin */ public static function getInfoOnInfoJson($_plugin='', $_what='') { if (($_plugin=='') || ($_what=='')) { $_plugin = ($_plugin=='')?'olindoteTools':$_plugin; log::add($_plugin, 'debug', '[olindoteTools::getInfoOnInfoJson()] _plugin or _what is empty // STOP'); return false; } $_jsonFile = getRootPath().'/plugins/'.$_plugin.'/plugin_info/info.json'; if (!file_exists($_jsonFile)) { log::add($_plugin, 'debug', '[olindoteTools::getInfoOnInfoJson()] _jsonFile="'.$_jsonFile.'", not exist ! // STOP'); return false; } return self::getJsonValue(file_get_contents($_jsonFile), $_what, $_plugin); } /** * Retourne le contenu d'une valeur Json * @param String $_data donnée au format json * @param String $_what valeur recherchée * @param String $_plugin nom du plugin */ public static function getJsonValue($_data, $_what, $_plugin='olindoteTools') { log::add($_plugin, 'debug', '[olindoteTools::getJsonValue()] _data='.$_data); $_jData = json_decode($_data,true); if ((is_array($_jData)) && (array_key_exists($_what, $_jData))) { log::add($_plugin, 'debug', '[olindoteTools::getJsonValue()] return ('.$_what.')= '.print_r($_jData,true)); return $_jData[$_what]; } else { log::add($_plugin, 'debug', '[olindoteTools::getJsonValue()] key ('.$_what.') not found in '.print_r($_jData,true)); return false; } } /** * Exécute un fichier SQL * @param String $_plugin nom du plugin * @param String $_name nom du fichier sql * @param String $_whatLog */ public static function execSQL($_plugin, $_name, $_whatLog='UPDATE') { if (($_whatLog=='INSTALL')||($_whatLog=='UPDATE')) { $_pluginLog = $_plugin.'_update'; } else { $_pluginLog = $_plugin; } if (($_plugin=='') || ($_name=='')) { $_plugin = ($_plugin=='')?'olindoteTools':$_plugin; log::add($_pluginLog, 'debug', '[olindoteTools::execSQL()] _plugin or _name is empty // STOP'); return false; } $_f = getRootPath().'/plugins/'.$_plugin.'/plugin_info/'.$_name.'.sql'; log::add($_pluginLog, 'info', '['.$_whatLog.'|execSQL()] verif sql file = "'.$_f.'"'); if (file_exists($_f)) { log::add($_pluginLog, 'info', '['.$_whatLog.'|execSQL()] sql file exist !'); try { exec('sudo chmod 777 '.$_f); $_sql = file_get_contents($_f); DB::Prepare($_sql, array(), DB::FETCH_TYPE_ROW); } catch(Exception $_e) { log::add($_pluginLog, 'info', '['.$_whatLog.'|execSQL()] ERROR/Exception : '.$_e); } log::add($_pluginLog, 'info', '['.$_whatLog.'|execSQL()] executed sql file: '.$_f); } } /** * Retourne le nom du paramètre en cache pour le contenu du Widget * @param string $_version version de l'affichage */ public static function getWidgetCacheName($_version, $_id) { $user_id = ''; if (isset($_SESSION) && isset($_SESSION['user']) && is_object($_SESSION['user'])) { $user_id = $_SESSION['user']->getId(); } return 'widgetHtml'.$_id.$_version.$user_id; } /** * Création d'un répertoire */ public static function checkAndCreateDirectory($_plugin='', $_path='') { if ($_plugin=='') $_plugin = 'olindoteTools'; if ($_path=='') { log::add($_plugin, 'debug', '[olindoteTools::checkAndCreateDirectory()] _path is empty // STOP'); return false; } $_path = cleanPath($_path); if (file_exists($_path)) { return true; } log::add($_plugin, 'debug', '[olindoteTools::checkAndCreateDirectory()] directory not exist ('.$_path.'), try to create it !'); //shell_exec('sudo mkdir -p '.$_path); //shell_exec('sudo chmod 755 -R '.$_path); //shell_exec('sudo chown -R www-data:www-data '.$_path); com_shell::execute(system::getCmdSudo().'mkdir -p '.$_path); com_shell::execute(system::getCmdSudo().'chmod 755 -R '.$_path); com_shell::execute(system::getCmdSudo().'chown '.system::get('www-uid').':'.system::get('www-gid').' '.$_path); if (file_exists($_path)) { return true; } log::add($_plugin, 'warning', '[olindoteTools::checkAndCreateDirectory()] directory can not be create ('.$_path.') !!??'); return false; } /** * Retourne le nom de la class de l'objet */ public static function getObjName($_obj=null) { if (!is_object($_obj)) return ''; return (substr(strtolower(get_class($_obj)),-3)=='cmd')?substr(get_class($_obj),0,-3):get_class($_obj); } } ?>