private function addMessages($project_id, $messagesArray)
 {
     $addMessage = new message();
     $userObj = new user();
     foreach ($messagesArray->{'post'} as $message) {
         $insid = 0;
         $title = $message->{'title'};
         $text = $message->{'body'};
         $uid = $message->{'author-id'};
         $user = $this->peopleHash["{$uid}"];
         $userProfile = $userObj->getProfile($user);
         $username = $userProfile["name"];
         $replies = $message->{'comments'};
         $insid = $addMessage->add($project_id, $title, $text, "", $user, $username, 0, 0);
         if ($insid > 0) {
             ++$this->msgCount;
             if (count($replies) > 0) {
                 foreach ($replies->{'comment'} as $reply) {
                     ++$this->msgCount;
                     $replytext = $reply->{"body"};
                     $ruid = $reply->{'author-id'};
                     $ruser = $this->peopleHash["{$ruid}"];
                     $ruserProfile = $userObj->getProfile($ruser);
                     $rusername = $ruserProfile["name"];
                     $addMessage->add($project_id, $replytext, $replytext, "", $ruser, $rusername, $insid, 0);
                 }
             }
         }
     }
 }
Example #2
0
 /**
  * Ajoute un message dans les log et fait en sorte qu'il n'y
  * ai jamais plus de 1000 lignes
  * @param string $_type type du message à mettre dans les log
  * @param string $_message message à mettre dans les logs
  */
 public static function add($_log, $_type, $_message, $_logicalId = '')
 {
     $_type = strtolower($_type);
     if ($_log != '' && $_type != '' && trim($_message) != '' && self::isTypeLog($_type)) {
         $_message = str_replace(";", ',', str_replace("\n", '<br/>', $_message));
         $path = self::getPathToLog($_log);
         $message = date("d-m-Y H:i:s") . ' | ' . $_type . ' | ' . $_message . "\r\n";
         $log = fopen($path, "a+");
         fputs($log, $message);
         fclose($log);
         if ($_type == 'error' && config::byKey('addMessageForErrorLog') == 1) {
             @message::add($_log, $_message, '', $_logicalId);
         }
     }
 }
Example #3
0
function add_message()
{
    safe('message');
    global $global, $smarty, $lang;
    $mes_type = post('type');
    $mes_username = post('username');
    $mes_email = post('email');
    $mes_title = post('title');
    $mes_text = post('text');
    $mes_show = post('show');
    if ($mes_type == '' || $mes_username == '' || $mes_email == '' || $mes_title == '' || $mes_text == '') {
        $info_text = $lang['submit_error_info'];
    } else {
        $mes_add_time = time();
        if ($mes_show != '2') {
            $mes_show = '0';
        }
        $obj = new message();
        $obj->set_value('mes_type', $mes_type);
        $obj->set_value('mes_username', $mes_username);
        $obj->set_value('mes_email', $mes_email);
        $obj->set_value('mes_title', $mes_title);
        $obj->set_value('mes_text', $mes_text);
        $obj->set_value('mes_add_time', $mes_add_time);
        $obj->set_value('mes_show', $mes_show);
        $obj->set_value('mes_lang', S_LANG);
        $obj->add();
        if (intval(get_varia('sentmail'))) {
            $email_title = '您的网站有了新的留言';
            $email_text = "[{$mes_type}] {$mes_title} <br /> {$mes_text}";
            call_send_email($email_title, $email_text, $mes_username, $mes_email);
        }
        $info_text = $lang['submit_message'];
    }
    $smarty->assign('info_text', $info_text);
    $smarty->assign('link_text', $lang['go_back']);
    $smarty->assign('link_href', url(array('channel' => 'message')));
}
Example #4
0
 public function execute(&$scenario = null)
 {
     if ($this->getOptions('enable', 1) == 0) {
         return;
     }
     $message = '';
     try {
         if ($this->getType() == 'element') {
             $element = scenarioElement::byId($this->getExpression());
             if (is_object($element)) {
                 $this->setLog($scenario, __('Exécution d\'un bloc élément : ', __FILE__) . $this->getExpression());
                 return $element->execute($scenario);
             }
             return;
         }
         $options = $this->getOptions();
         if (isset($options['enable'])) {
             unset($options['enable']);
         }
         if (is_array($options) && $this->getExpression() != 'wait') {
             foreach ($options as $key => $value) {
                 $options[$key] = str_replace('"', '', self::setTags($value, $scenario));
             }
         }
         if ($this->getType() == 'action') {
             if ($this->getExpression() == 'icon') {
                 if ($scenario != null) {
                     $options = $this->getOptions();
                     $this->setLog($scenario, __('Changement de l\'icone du scénario : ', __FILE__) . $options['icon']);
                     $scenario->setDisplay('icon', $options['icon']);
                     $scenario->save();
                 }
                 return;
             } else {
                 if ($this->getExpression() == 'wait') {
                     if (!isset($options['condition'])) {
                         return;
                     }
                     $result = false;
                     $occurence = 0;
                     $limit = isset($options['timeout']) && is_numeric($options['timeout']) ? $options['timeout'] : 7200;
                     while ($result !== true) {
                         $expression = self::setTags($options['condition'], $scenario);
                         $result = evaluate($expression);
                         if ($occurence > $limit) {
                             $this->setLog($scenario, __('[Wait] Condition valide par dépassement de temps', __FILE__));
                             return;
                         }
                         $occurence++;
                         sleep(1);
                     }
                     $this->setLog($scenario, __('[Wait] Condition valide : ', __FILE__) . $expression);
                     return;
                 } else {
                     if ($this->getExpression() == 'sleep') {
                         if (isset($options['duration'])) {
                             try {
                                 $options['duration'] = evaluate($options['duration']);
                             } catch (Exception $e) {
                             }
                             if (is_numeric($options['duration']) && $options['duration'] > 0) {
                                 $this->setLog($scenario, __('Pause de ', __FILE__) . $options['duration'] . __(' seconde(s)', __FILE__));
                                 if ($options['duration'] < 1) {
                                     return usleep($options['duration'] * 1000);
                                 } else {
                                     return sleep($options['duration']);
                                 }
                             }
                         }
                         $this->setLog($scenario, __('Aucune durée trouvée pour l\'action sleep ou la durée n\'est pas valide : ', __FILE__) . $options['duration']);
                         return;
                     } else {
                         if ($this->getExpression() == 'stop') {
                             if ($scenario != null) {
                                 $this->setLog($scenario, __('Arret du scénario', __FILE__));
                                 $scenario->setState('stop');
                                 $scenario->setPID('');
                                 $scenario->persistLog();
                                 $scenario->save();
                             }
                             die;
                         } else {
                             if ($this->getExpression() == 'log') {
                                 if ($scenario != null) {
                                     $scenario->setLog('Log : ' . $options['message']);
                                     if ($scenario->getConfiguration('speedPriority', 0) == 1) {
                                         $scenario->persistLog();
                                     }
                                 }
                                 return;
                             } else {
                                 if ($this->getExpression() == 'message') {
                                     message::add('scenario', $options['message']);
                                     return;
                                 } else {
                                     if ($this->getExpression() == 'equipement') {
                                         $eqLogic = eqLogic::byId(str_replace(array('#eqLogic', '#'), '', $this->getOptions('eqLogic')));
                                         if (!is_object($eqLogic)) {
                                             throw new Exception(__('Action sur l\'équipement impossible. Equipement introuvable - Vérifiez l\'id : ', __FILE__) . $this->getOptions('eqLogic'));
                                         }
                                         switch ($this->getOptions('action')) {
                                             case 'show':
                                                 $this->setLog($scenario, __('Equipement visible : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsVisible(1);
                                                 $eqLogic->save();
                                                 break;
                                             case 'hide':
                                                 $this->setLog($scenario, __('Equipement masqué : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsVisible(0);
                                                 $eqLogic->save();
                                                 break;
                                             case 'deactivate':
                                                 $this->setLog($scenario, __('Equipement désactivé : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsEnable(0);
                                                 $eqLogic->save();
                                                 break;
                                             case 'activate':
                                                 $this->setLog($scenario, __('Equipement activé : ', __FILE__) . $eqLogic->getHumanName());
                                                 $eqLogic->setIsEnable(1);
                                                 $eqLogic->save();
                                                 break;
                                         }
                                         return;
                                     } else {
                                         if ($this->getExpression() == 'say') {
                                             $this->setLog($scenario, __('Je dis : ', __FILE__) . $options['message']);
                                             nodejs::pushUpdate('jeedom::say', $options['message']);
                                             return;
                                         } else {
                                             if ($this->getExpression() == 'gotodesign') {
                                                 $this->setLog($scenario, __('Changement design : ', __FILE__) . $options['plan_id']);
                                                 nodejs::pushUpdate('jeedom::gotoplan', $options['plan_id']);
                                                 return;
                                             } else {
                                                 if ($this->getExpression() == 'return') {
                                                     $this->setLog($scenario, __('Je vais retourner : ', __FILE__) . $options['message']);
                                                     $scenario->setReturn($scenario->getReturn() . $options['message']);
                                                     return;
                                                 } else {
                                                     if ($this->getExpression() == 'scenario') {
                                                         if ($scenario != null && $this->getOptions('scenario_id') == $scenario->getId()) {
                                                             $actionScenario =& $scenario;
                                                         } else {
                                                             $actionScenario = scenario::byId($this->getOptions('scenario_id'));
                                                         }
                                                         if (!is_object($actionScenario)) {
                                                             throw new Exception($scenario, __('Action sur scénario impossible. Scénario introuvable - Vérifiez l\'id : ', __FILE__) . $this->getOptions('scenario_id'));
                                                         }
                                                         switch ($this->getOptions('action')) {
                                                             case 'start':
                                                                 $this->setLog($scenario, __('Lancement du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 if ($scenario != null) {
                                                                     $actionScenario->launch(false, __('Lancement provoqué par le scénario  : ', __FILE__) . $scenario->getHumanName());
                                                                 } else {
                                                                     $actionScenario->launch(false, __('Lancement provoqué', __FILE__));
                                                                 }
                                                                 break;
                                                             case 'stop':
                                                                 $this->setLog($scenario, __('Arrêt forcé du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->stop();
                                                                 break;
                                                             case 'deactivate':
                                                                 $this->setLog($scenario, __('Désactivation du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->setIsActive(0);
                                                                 $actionScenario->save();
                                                                 break;
                                                             case 'activate':
                                                                 $this->setLog($scenario, __('Activation du scénario : ', __FILE__) . $actionScenario->getName());
                                                                 $actionScenario->setIsActive(1);
                                                                 $actionScenario->save();
                                                                 break;
                                                         }
                                                         return;
                                                     } else {
                                                         if ($this->getExpression() == 'variable') {
                                                             $options['value'] = self::setTags($options['value']);
                                                             try {
                                                                 $result = evaluate($options['value']);
                                                                 if (!is_numeric($result)) {
                                                                     $result = $options['value'];
                                                                 }
                                                             } catch (Exception $ex) {
                                                                 $result = $options['value'];
                                                             }
                                                             $message = __('Affectation de la variable ', __FILE__) . $this->getOptions('name') . __(' => ', __FILE__) . $options['value'] . ' = ' . $result;
                                                             $this->setLog($scenario, $message);
                                                             $dataStore = new dataStore();
                                                             $dataStore->setType('scenario');
                                                             $dataStore->setKey($this->getOptions('name'));
                                                             $dataStore->setValue($result);
                                                             $dataStore->setLink_id(-1);
                                                             $dataStore->save();
                                                             return;
                                                         } else {
                                                             $cmd = cmd::byId(str_replace('#', '', $this->getExpression()));
                                                             if (is_object($cmd)) {
                                                                 if ($cmd->getSubtype() == 'slider' && isset($options['slider'])) {
                                                                     $options['slider'] = evaluate($options['slider']);
                                                                 }
                                                                 if (is_array($options) && count($options) != 0) {
                                                                     $this->setLog($scenario, __('Exécution de la commande ', __FILE__) . $cmd->getHumanName() . __(" avec comme option(s) : \n", __FILE__) . print_r($options, true));
                                                                 } else {
                                                                     $this->setLog($scenario, __('Exécution de la commande ', __FILE__) . $cmd->getHumanName());
                                                                 }
                                                                 if (is_object($scenario) && $scenario->getConfiguration('cmdNoWait', 0) == 1) {
                                                                     $options['speedAndNoErrorReport'] = true;
                                                                 }
                                                                 return $cmd->execCmd($options);
                                                             }
                                                             $this->setLog($scenario, __('[Erreur] Aucune commande trouvée pour ', __FILE__) . $this->getExpression());
                                                             return;
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if ($this->getType() == 'condition') {
                 $expression = self::setTags($this->getExpression(), $scenario, true);
                 $message = __('Evaluation de la condition : [', __FILE__) . $expression . '] = ';
                 $result = evaluate($expression);
                 if (is_bool($result)) {
                     if ($result) {
                         $message .= __('Vrai', __FILE__);
                     } else {
                         $message .= __('Faux', __FILE__);
                     }
                 } else {
                     $message .= $result;
                 }
                 $this->setLog($scenario, $message);
                 return $result;
             } else {
                 if ($this->getType() == 'code') {
                     $this->setLog($scenario, __('Exécution d\'un bloc code', __FILE__));
                     return eval($this->getExpression());
                 }
             }
         }
     } catch (Exception $e) {
         $this->setLog($scenario, $message . $e->getMessage());
     }
 }
Example #5
0
 public static function cron()
 {
     if (!self::isStarted()) {
         config::save('enableScenario', 1);
         config::save('enableCron', 1);
         $cache = cache::byKey('jeedom::usbMapping');
         $cache->remove();
         foreach (cron::all() as $cron) {
             if ($cron->running() && $cron->getClass() != 'jeedom' && $cron->getFunction() != 'cron') {
                 try {
                     $cron->halt();
                 } catch (Exception $e) {
                 }
             }
         }
         try {
             jeedom::start();
         } catch (Exception $e) {
         }
         try {
             plugin::start();
         } catch (Exception $e) {
         }
         touch('/tmp/jeedom_start');
         self::event('start');
         log::add('core', 'info', 'Démarrage de Jeedom OK');
     }
     self::isDateOk();
     try {
         $c = new Cron\CronExpression(config::byKey('update::check'), new Cron\FieldFactory());
         if ($c->isDue()) {
             $lastCheck = strtotime(config::byKey('update::lastCheck'));
             if (strtotime('now') - $lastCheck > 3600) {
                 if (config::byKey('update::auto') == 1) {
                     update::checkAllUpdate();
                     jeedom::update('', 0);
                 } else {
                     config::save('update::check', rand(1, 59) . ' ' . rand(6, 7) . ' * * *');
                     update::checkAllUpdate();
                     $updates = update::byStatus('update');
                     if (count($updates) > 0) {
                         $toUpdate = '';
                         foreach ($updates as $update) {
                             $toUpdate .= $update->getLogicalId() . ',';
                         }
                         message::add('update', __('De nouvelles mises à jour sont disponibles : ', __FILE__) . trim($toUpdate, ','), '', 'newUpdate');
                     }
                 }
             }
         }
         $c = new Cron\CronExpression('35 00 * * 0', new Cron\FieldFactory());
         if ($c->isDue()) {
             cache::clean();
             DB::optimize();
         }
         $c = new Cron\CronExpression('02 02 * * *', new Cron\FieldFactory());
         if ($c->isDue()) {
             try {
                 log::chunk();
                 cron::clean();
             } catch (Exception $e) {
                 log::add('log', 'error', $e->getMessage());
             }
         }
         $c = new Cron\CronExpression('21 23 * * *', new Cron\FieldFactory());
         if ($c->isDue()) {
             try {
                 scenario::cleanTable();
                 user::cleanOutdatedUser();
                 scenario::consystencyCheck();
             } catch (Exception $e) {
                 log::add('scenario', 'error', $e->getMessage());
             }
         }
     } catch (Exception $e) {
     }
 }
Example #6
0
 /**
  *
  * @param type $_options
  * @param type $cache 0 = ignorer le cache , 1 = mode normal, 2 = cache utilisé même si expiré (puis marqué à recollecter)
  * @return command result
  * @throws Exception
  */
 public function execCmd($_options = null, $cache = 1, $_sendNodeJsEvent = true, $_quote = false)
 {
     if ($this->getEventOnly() == 1) {
         $cache = 2;
     }
     if ($this->getType() == 'info' && $cache != 0) {
         $mc = cache::byKey('cmd' . $this->getId(), $cache == 2 ? true : false);
         if ($cache == 2 || !$mc->hasExpired()) {
             if ($mc->hasExpired()) {
                 $this->setCollect(1);
             }
             $this->setCollectDate($mc->getOptions('collectDate', $mc->getDatetime()));
             $this->setValueDate($mc->getOptions('valueDate', $mc->getDatetime()));
             return $mc->getValue();
         }
     }
     $eqLogic = $this->getEqLogic();
     if (!is_object($eqLogic) || $eqLogic->getIsEnable() != 1) {
         throw new Exception(__('Equipement désactivé - impossible d\'exécuter la commande : ' . $this->getHumanName(), __FILE__));
     }
     $eqLogic->emptyCacheWidget();
     try {
         if ($_options !== null && $_options !== '') {
             $options = self::cmdToValue($_options);
             if (is_json($_options)) {
                 $options = json_decode($_options, true);
             }
         } else {
             $options = null;
         }
         if (isset($options['color'])) {
             $options['color'] = str_replace('"', '', $options['color']);
         }
         if ($this->getSubType() == 'color' && isset($options['color']) && substr($options['color'], 0, 1) != '#') {
             $options['color'] = cmd::convertColor($options['color']);
         }
         if ($this->getType() == 'action') {
             log::add('event', 'event', __('Exécution de la commande ', __FILE__) . $this->getHumanName() . __(' avec les paramètres ', __FILE__) . str_replace(array("\n", '  ', 'Array'), '', print_r($options, true)));
         }
         $value = $this->formatValue($this->execute($options), $_quote);
     } catch (Exception $e) {
         //Si impossible de contacter l'équipement
         $type = $eqLogic->getEqType_name();
         if ($eqLogic->getConfiguration('nerverFail') != 1) {
             $numberTryWithoutSuccess = $eqLogic->getStatus('numberTryWithoutSuccess', 0);
             $eqLogic->setStatus('numberTryWithoutSuccess', $numberTryWithoutSuccess);
             if ($numberTryWithoutSuccess >= config::byKey('numberOfTryBeforeEqLogicDisable')) {
                 $message = 'Désactivation de <a href="' . $eqLogic->getLinkToConfiguration() . '">' . $eqLogic->getName();
                 $message .= '</a> car il n\'a pas répondu ou mal répondu lors des 3 derniers essais';
                 message::add($type, $message);
                 $eqLogic->setIsEnable(0);
                 $eqLogic->save();
             }
         }
         log::add($type, 'error', __('Erreur execution de la commande ', __FILE__) . $this->getHumanName() . ' : ' . $e->getMessage());
         throw $e;
     }
     if ($this->getType() == 'info' && $value !== false) {
         if ($this->getCollectDate() == '') {
             $this->setCollectDate(date('Y-m-d H:i:s'));
         }
         if ($this->getValueDate() == '') {
             $this->setValueDate(date('Y-m-d H:i:s'));
         }
         cache::set('cmd' . $this->getId(), $value, $this->getCacheLifetime(), array('collectDate' => $this->getCollectDate(), 'valueDate' => $this->getValueDate()));
         $this->setCollect(0);
         $nodeJs = array(array('cmd_id' => $this->getId()));
         foreach (self::byValue($this->getId()) as $cmd) {
             $nodeJs[] = array('cmd_id' => $cmd->getId());
         }
         nodejs::pushUpdate('eventCmd', $nodeJs);
     }
     if ($this->getType() != 'action' && !is_array($value) && strpos($value, 'error') === false) {
         if ($eqLogic->getStatus('numberTryWithoutSuccess') != 0) {
             $eqLogic->setStatus('numberTryWithoutSuccess', 0);
         }
         $eqLogic->setStatus('lastCommunication', date('Y-m-d H:i:s'));
     }
     if ($this->getType() == 'action' && $options !== null && $this->getValue() == '') {
         if (isset($options['slider'])) {
             $this->setConfiguration('lastCmdValue', $options['slider']);
             $this->save();
         }
         if (isset($options['color'])) {
             $this->setConfiguration('lastCmdValue', $options['color']);
             $this->save();
         }
     }
     if ($this->getType() == 'action' && $this->getConfiguration('updateCmdId') != '') {
         $cmd = cmd::byId($this->getConfiguration('updateCmdId'));
         if (is_object($cmd)) {
             $value = $this->getConfiguration('updateCmdToValue');
             switch ($this->getSubType()) {
                 case 'slider':
                     $value = str_replace('#slider#', $options['slider'], $value);
                     break;
                 case 'color':
                     $value = str_replace('#color#', $options['color'], $value);
                     break;
             }
             $cmd->event($value);
         }
     }
     return $value;
 }
Example #7
0
 if ($alliance->data['user'] == $_SESSION[$shortTitle . 'User']['id'] && $alliance->data['id'] == $_GET['recipient']) {
     $senderAlliance = new alliance();
     if ($senderAlliance->get('id', $_GET['sender']) == 'done') {
         $status = $alliance->acceptPeace($senderAlliance->data['id']);
         if ($status == 'done') {
             $user = new user();
             if ($user->get('id', $senderAlliance->data['user']) == 'done') {
                 $user->getPreferences('name');
                 if ($user->preferences['allianceReports']) {
                     $msg = new message();
                     $msg->data['sender'] = $_SESSION[$shortTitle . 'User']['name'];
                     $msg->data['recipient'] = $user->data['name'];
                     $msg->data['subject'] = $ui['peaceAccepted'];
                     $msg->data['body'] = $ui['sender'] . ': ' . $alliance->data['name'] . ' ' . $ui['alliance'];
                     $msg->data['viewed'] = 0;
                     $status = $msg->add();
                     if ($status == 'done') {
                         header('Location: alliance.php?action=get');
                     }
                 }
             } else {
                 $message = $ui['noUser'];
             }
         }
         $message = $ui[$status];
     } else {
         $message = $ui['noAlliance'];
     }
 } else {
     $message = $ui['accessDenied'];
 }
Example #8
0
    }
}
if ($action == "addform") {
    // display addform
    $template->display("addmessageform.tpl");
} elseif ($action == "add") {
    // check if the user is allowed to add messages
    if (!$userpermissions["messages"]["add"]) {
        $errtxt = $langfile["nopermission"];
        $noperm = $langfile["accessdenied"];
        $template->assign("errortext", "<h2>{$errtxt}</h2><br>{$noperm}");
        $template->display("error.tpl");
        die;
    }
    // add message
    $themsg = $msg->add($id, $title, $message, $userid, $username, 0, $milestone);
    if ($themsg) {
        if ($thefiles > 0) {
            // attach existing file
            $msg->attachFile($thefiles, $themsg);
        } elseif ($thefiles == 0 and $numfiles > 0) {
            // if upload files are set, upload and attach
            $msg->attachFile(0, $themsg, $id);
        }
        if ($settings["mailnotify"]) {
            $sendto = getArrayVal($_POST, "sendto");
            $usr = (object) new project();
            $users = $usr->getProjectMembers($id, 10000);
            if ($sendto[0] == "all") {
                $sendto = $users;
                $sendto = reduceArray($sendto);
Example #9
0
 public function batteryStatus($_pourcent, $_datetime = '')
 {
     if ($_pourcent > 20) {
         foreach (message::byPluginLogicalId($this->getEqType_name(), 'lowBattery' . $this->getId()) as $message) {
             $message->remove();
         }
         foreach (message::byPluginLogicalId($this->getEqType_name(), 'noBattery' . $this->getId()) as $message) {
             $message->remove();
         }
     } else {
         if ($_pourcent > 0 && $_pourcent <= 20) {
             $logicalId = 'lowBattery' . $this->getId();
             $message = 'Le module ' . $this->getEqType_name() . ' ';
             $message .= $this->getHumanName() . ' a moins de ' . $_pourcent . '% de batterie';
             if ($this->getConfiguration('battery_type') != '') {
                 $message .= ' (' . $this->getConfiguration('battery_type') . ')';
             }
             message::add($this->getEqType_name(), $message, '', $logicalId);
         } else {
             $logicalId = 'noBattery' . $this->getId();
             $message = __('Le module ', __FILE__) . $this->getEqType_name() . ' ';
             $message .= $this->getHumanName() . __(' n\'a plus de batterie (', __FILE__) . $_pourcent . ' %)';
             message::add($this->getEqType_name(), $message, '', $logicalId);
         }
     }
     $this->setConfiguration('batteryStatus', $_pourcent);
     if ($_datetime != '') {
         $this->setConfiguration('batteryStatusDatetime', $_datetime);
     } else {
         $this->setConfiguration('batteryStatusDatetime', date('Y-m-d H:i:s'));
     }
     $this->emptyCacheWidget();
     $this->save();
 }
Example #10
0
 public static function event()
 {
     $nodeId = init('n');
     $port = init('p');
     if (is_numeric(init('t'))) {
         $type = chr(init('t'));
     } else {
         $type = init('t');
     }
     $value = init('v');
     $jeenodeReal = jeenodeReal::byLogicalId($nodeId, 'jeenode');
     if (count($jeenodeReal) == 0) {
         log::add('jeenode', 'error', 'Jeenode id : ' . $nodeId . ' inconnue');
         return;
     }
     if (count($jeenodeReal) > 1) {
         log::add('jeenode', 'error', 'Jeenode id : ' . $nodeId . ' n\'est pas unique');
         return;
     }
     $jeenodeReal = $jeenodeReal[0];
     if (is_object($jeenodeReal)) {
         if ($type == 'b') {
             $linkToEquipement = 'index.php?v=d&p=jeenode&id=';
             $linkToEquipement .= $jeenodeReal->getId();
             $message = 'L\'équipement <a href="' . $linkToEquipement . '">' . $jeenodeReal->getName();
             $message .= '</a> à une batterie faible';
             message::add('jeenode', $message);
             return false;
         } else {
             $jeenode = $jeenodeReal->getPortNumber($port);
             if (is_object($jeenode)) {
                 $cmd = $jeenode->getCmdByType($type);
                 if (is_object($cmd)) {
                     $jeenodeReal->updateLastCommunication();
                     $cmd->event($value);
                 }
             }
         }
     }
 }
Example #11
0
             $scenario->setIsActive(0);
             $scenario->save();
             break;
         case 'activate':
             log::add('api', 'debug', 'Activation scénario de : ' . $scenario->getHumanName());
             $scenario->setIsActive(1);
             $scenario->save();
             break;
         default:
             throw new Exception('Action non trouvée ou invalide [start,stop,deactivate,activate]');
     }
     echo 'ok';
 } else {
     if ($type == 'message') {
         log::add('api', 'debug', 'Demande API pour ajouter un message');
         message::add(init('category'), init('message'));
     } else {
         if ($type == 'object') {
             log::add('api', 'debug', 'Demande API pour les objets');
             echo json_encode(utils::o2a(object::all()));
         } else {
             if ($type == 'eqLogic') {
                 log::add('api', 'debug', 'Demande API pour les équipements');
                 echo json_encode(utils::o2a(eqLogic::byObjectId(init('object_id'))));
             } else {
                 if ($type == 'command') {
                     log::add('api', 'debug', 'Demande API pour les commandes');
                     echo json_encode(utils::o2a(cmd::byEqLogicId(init('eqLogic_id'))));
                 } else {
                     if ($type == 'fulData') {
                         log::add('api', 'debug', 'Demande API pour les commandes');
Example #12
0
 public function checkCombat($time)
 {
     //		if($this->checkingCombat){return;}
     //		else{$this->checkingCombat = 1;}
     global $db, $game, $ui;
     $db->query('start transaction');
     $this->getQueue('combat');
     $ok = 1;
     foreach ($this->queue['combat'] as $combat) {
         $combat['end'] = $combat['start'] + floor($combat['duration'] * 60);
         if ($combat['end'] <= $time) {
             $otherNode = new node();
             if ($combat['sender'] == $this->data['id']) {
                 $nodes = array('attacker' => 'this', 'defender' => 'otherNode');
                 $status = $otherNode->get('id', $combat['recipient']);
             } else {
                 $nodes = array('attacker' => 'otherNode', 'defender' => 'this');
                 $status = $otherNode->get('id', $combat['sender']);
             }
             if (!$combat['stage']) {
                 if ($status == 'done') {
                     $data = array();
                     $data['input']['attacker']['focus'] = $combat['focus'];
                     $data['input']['attacker']['faction'] = ${$nodes}['attacker']->data['faction'];
                     $otherResult = $db->query('select * from combat_units where combat="' . $combat['id'] . '"');
                     while ($group = db::fetch($otherResult)) {
                         $data['input']['attacker']['groups'][] = array('unitId' => $group['id'], 'quantity' => $group['value']);
                     }
                     $data['input']['defender']['focus'] = ${$nodes}['defender']->data['focus'];
                     $data['input']['defender']['faction'] = ${$nodes}['defender']->data['faction'];
                     $otherNode->getUnits();
                     foreach (${$nodes}['defender']->units as $group) {
                         $data['input']['defender']['groups'][] = array('unitId' => $group['id'], 'quantity' => $group['value']);
                     }
                     $data = node::doCombat($data);
                     $captureNode = true;
                     ${$nodes}['defender']->getResources();
                     foreach ($data['output']['defender']['groups'] as $key => $group) {
                         $db->query('update units set value="' . $group['quantity'] . '" where node="' . ${$nodes}['defender']->data['id'] . '" and id="' . $group['unitId'] . '"');
                         if ($db->affected_rows() == -1) {
                             $ok = 0;
                         }
                         $lostCount = $data['input']['defender']['groups'][$key]['quantity'] - $group['quantity'];
                         if ($lostCount > 0) {
                             $upkeepResource = $game['units'][${$nodes}['defender']->data['faction']][$group['unitId']]['upkeepResource'];
                             $upkeep = $game['units'][${$nodes}['defender']->data['faction']][$group['unitId']]['upkeep'];
                             ${$nodes}['defender']->resources[$upkeepResource]['value'] += $upkeep * $lostCount;
                             $db->query('update resources set value="' . ${$nodes}['defender']->resources[$upkeepResource]['value'] . '" where node="' . ${$nodes}['defender']->data['id'] . '" and id="' . $upkeepResource . '"');
                             if ($db->affected_rows() == -1) {
                                 $ok = 0;
                             }
                         }
                         if ($group['quantity']) {
                             $captureNode = false;
                         }
                     }
                     foreach ($data['output']['attacker']['groups'] as $key => $group) {
                         $db->query('update combat_units set value="' . $group['quantity'] . '" where combat="' . $combat['id'] . '" and id="' . $group['unitId'] . '"');
                         if ($db->affected_rows() == -1) {
                             $ok = 0;
                         }
                     }
                     $start = strftime('%Y-%m-%d %H:%M:%S', $combat['end']);
                     $db->query('update combat set stage=1, start="' . $start . '" where id="' . $combat['id'] . '"');
                     if ($db->affected_rows() == -1) {
                         $ok = 0;
                     }
                     if ($captureNode) {
                         $db->query('update nodes set user="******" where id="' . ${$nodes}['defender']->data['id'] . '"');
                         if ($db->affected_rows() == -1) {
                             $ok = 0;
                         }
                     }
                     //send reports; to be ported to an addon (remember to remove global "$ui")
                     if ($data['output']['attacker']['winner']) {
                         $attackerOutcome = $ui['won'];
                     } else {
                         $attackerOutcome = $ui['lost'];
                     }
                     if ($data['output']['defender']['winner']) {
                         $defenderOutcome = $ui['won'];
                     } else {
                         $defenderOutcome = $ui['lost'];
                     }
                     $msgBody = '<div style="text-align: center;">';
                     foreach ($data['output']['attacker']['groups'] as $key => $group) {
                         $msgBody .= '<div class="cell"><div class="unitBlock"><img class="unitBlock" src="templates/default/images/units/' . ${$nodes}['attacker']->data['faction'] . '/' . $group['unitId'] . '.png"></div><div class="unitBlock">' . $data['input']['attacker']['groups'][$key]['quantity'] . '</div><div class="unitBlock">' . $group['quantity'] . '</div></div>';
                     }
                     $msgBody .= '</div><div style="text-align: center;">' . $attackerOutcome . '</div><div style="text-align: center;">-----</div><div style="text-align: center;">' . $defenderOutcome . '</div><div style="text-align: center;">';
                     foreach ($data['output']['defender']['groups'] as $key => $group) {
                         if ($data['input']['defender']['groups'][$key]['quantity']) {
                             $msgBody .= '<div class="cell"><div class="unitBlock">' . $group['quantity'] . '</div><div class="unitBlock">' . $data['input']['defender']['groups'][$key]['quantity'] . '</div><div class="unitBlock"><img class="unitBlock" src="templates/default/images/units/' . ${$nodes}['defender']->data['faction'] . '/' . $group['unitId'] . '.png"></div></div>';
                         }
                     }
                     $msgBody .= '</div>';
                     $msgBody = $db->real_escape_string($msgBody);
                     $attackerUser = new user();
                     if ($attackerUser->get('id', ${$nodes}['attacker']->data['user']) == 'done') {
                         $attackerUser->getPreferences('name');
                         if ($attackerUser->preferences['combatReports']) {
                             $msg = new message();
                             $msg->data['sender'] = $attackerUser->data['name'];
                             $msg->data['recipient'] = $attackerUser->data['name'];
                             $msg->data['subject'] = $ui['combatReport'] . ' - ' . ${$nodes}['defender']->data['name'];
                             $msg->data['body'] = $msgBody;
                             $msg->data['viewed'] = 0;
                             $msg->add();
                         }
                     }
                     $defenderUser = new user();
                     if ($defenderUser->get('id', ${$nodes}['defender']->data['user']) == 'done') {
                         $defenderUser->getPreferences('name');
                         if ($defenderUser->preferences['combatReports']) {
                             $msg = new message();
                             $msg->data['sender'] = $defenderUser->data['name'];
                             $msg->data['recipient'] = $defenderUser->data['name'];
                             $msg->data['subject'] = $ui['combatReport'] . ' - ' . ${$nodes}['defender']->data['name'];
                             $msg->data['body'] = $msgBody;
                             $msg->data['viewed'] = 0;
                             $msg->add();
                         }
                     }
                     //\send reports
                 }
             } else {
                 ${$nodes}['attacker']->getResources();
                 $result = $db->query('select * from combat_units where combat="' . $combat['id'] . '"');
                 while ($group = db::fetch($result)) {
                     $db->query('update units set value="' . $group['value'] . '" where node="' . $combat['sender'] . '" and id="' . $group['id'] . '"');
                     if ($db->affected_rows() == -1) {
                         $ok = 0;
                     }
                     $upkeepResource = $game['units'][${$nodes}['attacker']->data['faction']][$group['id']]['upkeepResource'];
                     $upkeep = $game['units'][${$nodes}['attacker']->data['faction']][$group['id']]['upkeep'];
                     $this->resources[$upkeepResource]['value'] -= $upkeep * $group['value'];
                     $db->query('update resources set value="' . ${$nodes}['attacker']->resources[$upkeepResource]['value'] . '" where node="' . ${$nodes}['attacker']->data['id'] . '" and id="' . $upkeepResource . '"');
                     if ($db->affected_rows() == -1) {
                         $ok = 0;
                     }
                 }
                 $db->query('delete from combat_units where combat="' . $combat['id'] . '"');
                 if ($db->affected_rows() == -1) {
                     $ok = 0;
                 }
                 $db->query('delete from combat where id="' . $combat['id'] . '"');
                 if ($db->affected_rows() == -1) {
                     $ok = 0;
                 }
             }
         }
     }
     if ($ok) {
         $db->query('commit');
     } else {
         $db->query('rollback');
     }
 }
Example #13
0
             $msg = 0;
         } else {
             if ($msg->data['recipient'] != $_SESSION[$shortTitle . 'User']['id']) {
                 $msg = 0;
             }
         }
     }
     if (isset($_POST['recipient'], $_POST['subject'], $_POST['body'])) {
         if ($_POST['recipient'] != '' && $_POST['subject'] != '' && $_POST['body'] != '') {
             $msg = new message();
             $msg->data['sender'] = $_SESSION[$shortTitle . 'User']['name'];
             $msg->data['recipient'] = $_POST['recipient'];
             $msg->data['subject'] = $_POST['subject'];
             $msg->data['body'] = $_POST['body'];
             $msg->data['viewed'] = 0;
             $message = $ui[$msg->add()];
         } else {
             $message = $ui['insufficientData'];
         }
     }
     break;
 case 'remove':
     if (isset($_GET['messageId'])) {
         $msg = new message();
         $status = $msg->get($_GET['messageId']);
         if ($status == 'done') {
             if ($msg->data['recipient'] == $_SESSION[$shortTitle . 'User']['id']) {
                 $status = message::remove($_GET['messageId']);
                 if ($status == 'done') {
                     header('location: message.php?action=list');
                 } else {