Esempio n. 1
0
 function template()
 {
     global $self;
     global $html;
     global $translationAdminPages;
     if (!isset($translationAdminPages)) {
         $translation = 'Admin Pages';
     }
     $html = template_replace("plugin:ADMINPAGES", "<a href='{$self}" . "action=admin_pages'>{$translationAdminPages}</a>", $html);
 }
 function template()
 {
     global $CON;
     $footnotes = array("<ol id=\"footnotes\">");
     foreach ($this->ft as $idx => $f) {
         $footnotes[] = "<li><a name=\"ft_down_" . ($idx + 1) . "\" href=\"#ft_up_" . ($idx + 1) . "\">&uarr;</a>{$f}</li>";
     }
     $footnotes[] = "</ol>";
     $CON = template_replace("plugin:FOOT_NOTES", implode("\n", $footnotes), $CON);
 }
 function template()
 {
     global $html, $page, $START_PAGE, $WIKI_TITLE, $TITLE, $self;
     if (!empty($page) && $this->link_page_title) {
         $page_nolang = preg_replace("/\\.[A-Za-z]{2}(-[A-Za-z]{2})?\$/", "", $page);
         $html = template_replace("plugin:WHAT_LINKS_HERE", "<a href=\"{$self}?action=whatlinkshere&amp;page=" . u($page_nolang) . "\" rel=\"nofollow\">What links here?</a>", $html);
         $html = template_replace("PAGE_TITLE", "<a href=\"{$self}?action=whatlinkshere&amp;page=" . u($page_nolang) . "\" rel=\"nofollow\" title=\"What links to this page?\">" . h($page == $START_PAGE && $page == $TITLE ? $WIKI_TITLE : $TITLE) . "</a>", $html);
     }
     if ($_GET["action"] == "whatlinkshere") {
         $html = template_replace("SHOW_PAGE", "<a href=\"{$self}?page=" . u($page_nolang) . "\" rel=\"nofollow\">{$GLOBALS['T_SHOW_PAGE']}</a>", $html);
     }
 }
Esempio n. 4
0
 function template()
 {
     global $html, $page, $action, $TEMPLATE, $CON;
     $select = "\r\n<form action=\"{$self}\" method=\"get\">\r\n<input type=\"hidden\" name=\"page\" value=\"" . h($page) . "\" />\r\n<input type=\"hidden\" name=\"action\" value=\"" . h($action) . "\" />\r\n<input type=\"hidden\" name=\"permanent\" value=\"1\" />\r\n<select name=\"template\" id=\"selectTemplate\" onchange=\"this.form.submit();\">\r\n";
     foreach ($this->tpls as $t_file => $t_name) {
         $selected = $TEMPLATE == $t_file ? " selected " : "";
         $select .= "<option value=\"{$t_file}\"{$selected}>" . h($t_name) . "</option>\n";
     }
     $select .= "</select></form>\n";
     $html = template_replace("plugin:SELECT_TEMPLATE", $select, $html);
     $CON = template_replace("SELECT_TEMPLATE", $select, $CON);
 }
Esempio n. 5
0
 function template()
 {
     global $html;
     global $PG_DIR;
     $side_menu = '';
     if (file_exists($PG_DIR . "side_menu.txt")) {
         $side_menu = file_get_contents($PG_DIR . "side_menu.txt");
     } else {
         $file = @fopen($PG_DIR . "side_menu.txt", 'w');
         fwrite($file, '');
         fclose($file);
     }
     $html = template_replace("plugin:SIDEMENU", $side_menu, $html);
 }
 function formatFinished()
 {
     global $CON, $content, $self, $showsource, $page, $esum, $error, $preview, $action, $html;
     global $T_PASSWORD, $T_EDIT_SUMMARY, $T_PREVIEW, $T_DONE, $T_DISCARD_CHANGES;
     if (!$_REQUEST["ajax"]) {
         return;
     } else {
         if ($action != "edit" && !$preview) {
             $CON = substr($CON, strpos($CON, ">") + 1);
             // $CON contains <div class="pre-div"> ... </div> and we don't want this "wrapper"
             $CON = substr($CON, 0, strlen($CON) - 6);
             die($CON);
         }
     }
     $rows = count(explode("\n", $CON));
     if ($this->rows_min > $rows) {
         $rows = $this->rows_min;
     } else {
         if ($this->rows_max < $rows) {
             $rows = $this->rows_max;
         }
     }
     if (!authentified() && !$showsource) {
         // if not logged on, require password
         $FORM_PASSWORD = $T_PASSWORD;
         $FORM_PASSWORD_INPUT = "<input class=\"ajaxPasswordInput\" type=\"password\" name=\"sc\" />";
     }
     $CON_FORM_BEGIN = "<form action=\"{$self}\" class=\"ajaxForm\" method=\"post\"><input type=\"hidden\" name=\"action\" value=\"save\" /><input class=\"ajaxShowSource\" type=\"hidden\" name=\"showsource\" value=\"{$showsource}\" />";
     $CON_FORM_END = "</form>";
     $CON_TEXTAREA = "<textarea name=\"content\" class=\"ajaxContentTextarea contentTextarea\" cols=\"83\" rows=\"{$rows}\">" . h($content ? $content : $CON) . "</textarea><input type=\"hidden\" id=\"ajaxPage\" name=\"page\" value=\"" . h($page) . "\" />";
     if (!$showsource) {
         $CON_SUBMIT = "<input class=\"submit ajaxContentSubmit\" onclick=\"ajaxAction('save', this);return false;\" type=\"submit\" value=\"{$T_DONE}\" />";
         $EDIT_SUMMARY_TEXT = $T_EDIT_SUMMARY;
         $EDIT_SUMMARY = "<input type=\"text\" name=\"esum\" class=\"ajaxEsum\" value=\"" . h($esum) . "\" />";
     }
     $CON_PREVIEW = "<input class=\"ajaxContentPreview\" class=\"submit\" onclick=\"ajaxAction('save&preview=1', this);return false;\" type=\"submit\" name=\"preview\" value=\"{$T_PREVIEW}\" /> <input type=\"submit\" onclick=\"ajaxAction('', this);return false;\" value=\"{$T_DISCARD_CHANGES}\" />";
     $subs = array(array("CONTENT_FORM", $CON_FORM_BEGIN), array("\\/CONTENT_FORM", $CON_FORM_END), array("CONTENT_TEXTAREA", $CON_TEXTAREA), array("FORM_PASSWORD", $FORM_PASSWORD), array("FORM_PASSWORD_INPUT", $FORM_PASSWORD_INPUT), array("EDIT_SUMMARY_TEXT", $EDIT_SUMMARY_TEXT), array("EDIT_SUMMARY_INPUT", $EDIT_SUMMARY), array("CONTENT_SUBMIT", $CON_SUBMIT), array("CONTENT_PREVIEW", $CON_PREVIEW), array("ERROR", $error));
     $html = @file_get_contents($GLOBALS["PLUGINS_DIR"] . "/AjaxEditing/template.html");
     plugin("template");
     // plugin specific template substitutions
     foreach ($subs as $s) {
         $html = template_replace($s[0], $s[1], $html);
     }
     $html = preg_replace("/\\{([^}]* )?plugin:.+( [^}]*)?\\}/U", "", $html);
     // getting rid of absent plugin tags
     die(($preview ? $CON : "") . $html);
 }
 function template()
 {
     global $self, $html, $LANG, $LANG_DIR, $CON, $action, $page;
     $langs = array();
     if (is_dir($LANG_DIR) && ($dir = opendir($LANG_DIR))) {
         // common plugins
         while (($file = readdir($dir)) !== false) {
             if (!is_dir($LANG_DIR . $file)) {
                 $langs[] = basename($file, ".php");
             }
         }
     }
     sort($langs);
     $select = "\n<form action=\"{$self}\" id=\"formSelectLanguage\" method=\"get\">\n<input type=\"hidden\" name=\"page\" value=\"" . basename($page, ".{$LANG}") . "\" />\n<input type=\"hidden\" name=\"action\" value=\"" . h($action) . "\" />\n<select name=\"lang\" id=\"selectLanguage\" onchange=\"this.form.submit();\">\n";
     foreach ($langs as $l) {
         $selected = $l == $LANG ? " selected=\"selected\" " : "";
         $select .= "<option value=\"" . h($l) . "\"{$selected}>" . h($this->lang_names[$l]) . "</option>\n";
     }
     $select .= "</select></form>\n";
     $html = template_replace("plugin:SELECT_LANGUAGE", $select, $html);
     $CON = str_replace("{SELECT_LANGUAGE}", $select, $CON);
 }
 function template()
 {
     global $CON, $html, $page, $PG_DIR, $action, $self;
     if (!empty($action)) {
         return;
     }
     if (($pos = strpos($page, ".")) !== false) {
         $p = preg_quote(substr($page, 0, $pos));
     } else {
         $p = preg_quote($page);
     }
     $versions = array();
     if ($dir = @opendir($PG_DIR)) {
         while ($file = readdir($dir)) {
             if (preg_match("/{$p}\\.([a-z\\-]+)\\.txt|{$p}\\.txt/", $file, $match)) {
                 $versions[isset($match[1]) ? $match[1] : $this->default_lang] = $p;
             }
         }
     }
     ksort($versions);
     if (count($versions) == 1) {
         array_pop($versions);
     }
     $arr_versions = array();
     foreach ($versions as $code => $art) {
         $arr_versions[] = "<a href=\"{$self}?page=" . u(basename($art, ".txt") . ".{$code}") . "\">" . h(trim($this->lang_names[$code])) . "</a>";
     }
     if (!empty($arr_versions)) {
         $ul_list = "<ul class=\"subpage\"><li>\n" . implode("</li><li>\n", $arr_versions) . "</li></ul>";
     }
     $CON = template_replace("VERSIONS", $ul_list, $CON);
     $html = template_replace("plugin:VERSIONS", $ul_list, $html);
     if (!empty($arr_versions)) {
         $p_list = implode(", ", $arr_versions);
     }
     $CON = template_replace("VERSIONS_LIST", $p_list, $CON);
     $html = template_replace("plugin:VERSIONS_LIST", $p_list, $html);
 }
Esempio n. 9
0
 public function toHtml($_version)
 {
     if ($this->getIsEnable() != 1) {
         return '';
     }
     if (!$this->hasRight('r')) {
         return '';
     }
     $_version = jeedom::versionAlias($_version);
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getIsEnable() ? $this->getName() : '<del>' . $this->getName() . '</del>', '#background_color#' => $this->getBackgroundColor($_version), '#eqLink#' => $this->getLinkToConfiguration());
     $Departs = $this->getCmd(null, 'Departs');
     $replace['#Departs#'] = is_object($Departs) ? $Departs->execCmd() : '';
     $RefreshAction = $this->getCmd(null, 'RefreshAction');
     $replace['#refresh_id#'] = is_object($RefreshAction) ? $RefreshAction->getId() : '';
     return template_replace($replace, getTemplate('core', $_version, 'eqlogic', 'trains'));
 }
Esempio n. 10
0
 public function toHtml($_version = 'dashboard')
 {
     if ($this->getConfiguration('noSpecifyWidget', 0) == 1) {
         return parent::toHtml($_version);
     }
     if ($_version == '') {
         throw new Exception(__('La version demandée ne peut pas être vide (mobile, dashboard ou scénario)', __FILE__));
     }
     if (!$this->hasRight('r')) {
         return '';
     }
     $version = jeedom::versionAlias($_version);
     if ($this->getDisplay('hideOn' . $version) == 1) {
         return '';
     }
     $cmd_html = '';
     $version = jeedom::versionAlias($_version);
     $vcolor = 'cmdColor';
     if ($version == 'mobile') {
         $vcolor = 'mcmdColor';
     }
     if ($this->getPrimaryCategory() == '') {
         $cmdColor = '';
     } else {
         $cmdColor = jeedom::getConfiguration('eqLogic:category:' . $this->getPrimaryCategory() . ':' . $vcolor);
     }
     $maps = array();
     $dynamic = array();
     $cmd_html = '';
     if ($this->getIsEnable()) {
         foreach ($this->getCmd(null, null, true) as $cmd) {
             if ($cmd->getConfiguration('mode') == 'travelTime') {
                 $from = $cmd->getConfiguration('from');
                 $to = $cmd->getConfiguration('to');
                 if (!isset($maps[$from . '_' . $to])) {
                     $maps[$from . '_' . $to] = array();
                 }
                 $maps[$from . '_' . $to]['travelTime'] = $cmd->execCmd();
             }
             if ($cmd->getConfiguration('mode') == 'distance') {
                 $from = $cmd->getConfiguration('from');
                 $to = $cmd->getConfiguration('to');
                 if (!isset($maps[$from . '_' . $to])) {
                     $maps[$from . '_' . $to] = array();
                 }
                 $maps[$from . '_' . $to]['distance'] = $cmd->execCmd();
             }
             if ($cmd->getConfiguration('mode') == 'travelDistance') {
                 $from = $cmd->getConfiguration('from');
                 $to = $cmd->getConfiguration('to');
                 if (!isset($maps[$from . '_' . $to])) {
                     $maps[$from . '_' . $to] = array();
                 }
                 $maps[$from . '_' . $to]['travelDistance'] = $cmd->execCmd();
             }
             if ($cmd->getConfiguration('mode') == 'dynamic') {
                 $dynamic[$cmd->getId()] = $cmd;
             }
         }
     }
     foreach ($maps as $key => $map) {
         $key = explode('_', $key);
         if (count($key) != 2) {
             continue;
         }
         foreach ($dynamic as $id => $cmd) {
             if (in_array($id, $key)) {
                 unset($dynamic[$id]);
             }
         }
         $from_cmd = cmd::byId($key[0]);
         $to_cmd = cmd::byId($key[1]);
         if (!is_object($from_cmd) || !is_object($to_cmd)) {
             contine;
         }
         $from = $from_cmd->execCmd();
         $to = $to_cmd->execCmd();
         $replace = array('#name#' => $from_cmd->getName() . ' <i class="fa fa-arrow-right"></i> ' . $to_cmd->getName(), '#from#' => $from, '#collectDate#' => $from_cmd->getCollectDate() > $to_cmd->getCollectDate() ? $from_cmd->getCollectDate() : $to_cmd->getCollectDate(), '#to#' => $to, '#travelDistance#' => isset($map['travelDistance']) ? $map['travelDistance'] : __('Inconnue', __FILE__), '#distance#' => isset($map['distance']) ? $map['distance'] : __('Inconnue', __FILE__), '#travelTime#' => isset($map['travelTime']) ? $map['travelTime'] : __('Inconnue', __FILE__));
         $cmd_html .= template_replace($replace, getTemplate('core', $version, 'geoloc', 'geoloc'));
     }
     foreach ($dynamic as $id => $cmd) {
         $replace = array('#state#' => $cmd->execCmd(), '#name#' => $cmd->getName(), '#collectDate#' => $cmd->getCollectDate(), '#id#' => $cmd->getId());
         $cmd_html .= template_replace($replace, getTemplate('core', $_version, 'geoloc_single', 'geoloc'));
     }
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getName(), '#eqLink#' => $this->hasRight('w') ? $this->getLinkToConfiguration() : '#', '#category#' => $this->getPrimaryCategory(), '#background_color#' => $this->getBackgroundColor($version), '#cmd#' => $cmd_html, '#style#' => '', '#noResize#' => 1, '#max_width#' => '650px', '#logicalId#' => $this->getLogicalId(), '#battery#' => $this->getConfiguration('batteryStatus', -2), '#batteryDatetime#' => $this->getConfiguration('batteryStatusDatetime', __('inconnue', __FILE__)));
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotShowObjectNameOnView', 0) == 0) {
         $object = $this->getObject();
         $replace['#object_name#'] = is_object($object) ? '(' . $object->getName() . ')' : '';
     } else {
         $replace['#object_name#'] = '';
     }
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotShowNameOnView') == 1) {
         $replace['#name#'] = '';
     }
     if (($_version == 'mobile' || $_version == 'dashboard') && $this->getDisplay('doNotShowNameOnDashboard') == 1) {
         $replace['#name#'] = '';
     }
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotDisplayBatteryLevelOnView') == 1) {
         $replace['#battery#'] = -1;
     }
     if ($_version == 'dashboard' && $this->getDisplay('doNotDisplayBatteryLevelOnDashboard') == 1) {
         $replace['#battery#'] = -1;
     }
     $parameters = $this->getDisplay('parameters');
     if (is_array($parameters)) {
         foreach ($parameters as $key => $value) {
             $replace['#' . $key . '#'] = $value;
         }
     }
     return template_replace($replace, getTemplate('core', $version, 'eqLogic'));
 }
Esempio n. 11
0
 function formatBegin()
 {
     global $CON;
     $CON = template_replace("INDEX_COMMA", $this->pagesList("comma"), $CON);
     $CON = template_replace("INDEX_LIST", $this->pagesList("list"), $CON);
 }
Esempio n. 12
0
 public function toHtml($_version = 'dashboard')
 {
     if ($this->getIsEnable() != 1) {
         return '';
     }
     if (!$this->hasRight('r')) {
         return '';
     }
     $version = jeedom::versionAlias($_version);
     if ($this->getDisplay('hideOn' . $version) == 1) {
         return '';
     }
     $mc = cache::byKey('porkfolioWidget' . jeedom::versionAlias($_version) . $this->getId());
     if ($mc->getValue() != '') {
         return preg_replace("/" . preg_quote(self::UIDDELIMITER) . "(.*?)" . preg_quote(self::UIDDELIMITER) . "/", self::UIDDELIMITER . mt_rand() . self::UIDDELIMITER, $mc->getValue());
     }
     $background = $this->getBackgroundColor($_version);
     if ($this->getCmd(null, 'derniervers')->execCmd() < 0) {
         $humeur = 'triste';
     } else {
         $humeur = 'content';
     }
     if ($this->getCmd(null, 'somme')->execCmd() >= $this->getCmd(null, 'objectif')->execCmd()) {
         $humeur = 'jeedom';
         $background = '#34a729';
     }
     if ($this->getCmd(null, 'somme')->execCmd() == 0) {
         $background = '#e54016';
         $humeur = 'very_triste';
     }
     $replace = array('#name#' => $this->getName(), '#id#' => $this->getId(), '#background_color#' => $background, '#uid#' => 'porkfolio' . $this->getId() . self::UIDDELIMITER . mt_rand() . self::UIDDELIMITER, '#eqLink#' => $this->getLinkToConfiguration(), '#porky_humeur#' => $humeur);
     foreach ($this->getCmd('info') as $cmd) {
         $replace['#' . $cmd->getLogicalId() . '_history#'] = '';
         if ($cmd->getIsVisible() == 1) {
             $replace['#' . $cmd->getLogicalId() . '_id#'] = $cmd->getId();
             if ($cmd->getName() == 'Date dépot' || $cmd->getName() == 'Date retournement' || $cmd->getName() == 'Date mouvement') {
                 $replace['#' . $cmd->getLogicalId() . '#'] = date("d/m/y H:i:s", $cmd->execCmd());
             } else {
                 $replace['#' . $cmd->getLogicalId() . '#'] = $cmd->execCmd();
             }
             $replace['#' . $cmd->getLogicalId() . '_collect#'] = $cmd->getCollectDate();
             if ($cmd->getIsHistorized() == 1) {
                 $replace['#' . $cmd->getLogicalId() . '_history#'] = 'history cursor';
             }
         } else {
             $replace['#' . $cmd->getLogicalId() . '#'] = '';
         }
     }
     $refresh = $this->getCmd(null, 'refresh');
     $replace['#refresh_id#'] = $refresh->getId();
     $parameters = $this->getDisplay('parameters');
     if (is_array($parameters)) {
         foreach ($parameters as $key => $value) {
             $replace['#' . $key . '#'] = $value;
         }
     }
     $html = template_replace($replace, getTemplate('core', $_version, 'porkfolio', 'porkfolio'));
     cache::set('porkfolioWidget' . $_version . $this->getId(), $html, 0);
     return $html;
 }
Esempio n. 13
0
 public static function dns_start()
 {
     if (config::byKey('ngrok::addr') == '') {
         return;
     }
     network::dns_stop();
     $config_file = '/tmp/ngrok_jeedom';
     $logfile = log::getPathToLog('ngrok');
     $uname = posix_uname();
     if (strrpos($uname['machine'], 'arm') !== false) {
         $cmd = dirname(__FILE__) . '/../../script/ngrok/ngrok-arm';
     } else {
         if ($uname['machine'] == 'x86_64') {
             $cmd = dirname(__FILE__) . '/../../script/ngrok/ngrok-x64';
         } else {
             $cmd = dirname(__FILE__) . '/../../script/ngrok/ngrok-x86';
         }
     }
     exec('chmod +x ' . $cmd);
     $cmd .= ' -config=' . $config_file . ' start jeedom';
     if (!self::dns_run()) {
         $replace = array('#server_addr#' => 'dns.jeedom.com:4443', '#name#' => 'jeedom', '#proto#' => 'https', '#port#' => 80, '#remote_port#' => '', '#token#' => config::byKey('ngrok::token'), '#auth#' => '', '#subdomain#' => 'subdomain : ' . config::byKey('ngrok::addr'));
         $config = template_replace($replace, file_get_contents(dirname(__FILE__) . '/../../script/ngrok/config'));
         if (file_exists($config_file)) {
             unlink($config_file);
         }
         file_put_contents($config_file, $config);
         log::remove('ngrok');
         log::add('ngork', 'debug', 'Lancement de ngork : ' . $cmd);
         exec($cmd . ' >> /dev/null 2>&1 &');
     }
     return true;
 }
Esempio n. 14
0
 * Limesurvey functions
 */
include "functions/functions.limesurvey.php";
$js = array("js/popup.js", "include/jquery/jquery-1.4.2.min.js", "include/jquery-ui/jquery-ui.min.js");
if (AUTO_LOGOUT_MINUTES !== false) {
    $js[] = "js/childnap.js";
}
xhtml_head(T_("Respondent Selection") . " - " . T_("Call back"), true, array("include/bootstrap/css/bootstrap.min.css", "css/rs.css"), $js);
$operator_id = get_operator_id();
$case_id = get_case_id($operator_id);
$questionnaire_id = get_questionnaire_id($operator_id);
//display introduction text
$sql = "SELECT rs_callback\r\n\tFROM questionnaire\r\n\tWHERE questionnaire_id = '{$questionnaire_id}'";
$r = $db->GetRow($sql);
if (!empty($r['rs_callback'])) {
    print "<div class='rstext well rs'>" . template_replace($r['rs_callback'], $operator_id, $case_id) . "</div>";
}
print "<p class='rstext alert alert-info'>" . T_("Survey is") . "&emsp;" . round(limesurvey_percent_complete($case_id), 1) . "&ensp;%&emsp;" . T_("complete") . "</p>";
print "<div class=' '>\r\n\t\t<div class='col-lg-2'><p><a class='btn btn-default' href=\"rs_intro.php\" >" . T_("Go Back") . "</a></p></div>";
//filter displayed outcomes
if ($questionnaire_id) {
    $outcomes = $db->GetOne("SELECT q.outcomes FROM `questionnaire` as q WHERE q.questionnaire_id = {$questionnaire_id}");
    //
    $outcomes = explode(",", $outcomes);
    if (in_array(8, $outcomes)) {
        $des = $db->GetAll("SELECT description FROM outcome WHERE outcome_id = 8");
        print "<div class='col-lg-4'><p class=''><h4 class=' '>" . T_("End call with outcome:") . "</h4></p>\r\n\t\t\t\t\t<p><a class='btn btn-primary' ";
        if (ALTERNATE_INTERFACE) {
            print "href=\"javascript:parent.location.href = 'index_interface2.php?outcome=8&amp;endcase=endcase'\">";
        } else {
            print "href=\"javascript:parent.poptastic('call.php?defaultoutcome=8');\">";
Esempio n. 15
0
 function template()
 {
     global $CON, $html, $action, $preview, $page, $PG_DIR, $HEAD, $self, $comments_html, $comment_captcha_failed;
     /*
      * Include comments if:
      * - {plugin:COMMENTS} is in template and {NO_COMMENTS} is not in page content
      * - {COMMENTS} is in page content
      */
     if ($action == "" && !$preview && (template_match("plugin:COMMENTS", $html, $null) && strpos($CON, "{NO_COMMENTS}") === false || strpos($CON, "{COMMENTS}") !== false)) {
         $HEAD .= '<script type="text/javascript" src="plugins/Comments/comments.js"></script>';
         $HEAD .= '<style type="text/css" media="all">@import url("plugins/Comments/comments.css");</style>';
         $tmpl = file_get_contents($this->data_dir . $this->template);
         $tmpl = strtr($tmpl, array("{FORM_NAME}" => $this->TP_FORM_NAME, "{FORM_EMAIL}" => $this->TP_FORM_EMAIL, "{FORM_CONTENT}" => $this->TP_FORM_CONTENT, "{FORM_NAME_VALUE}" => $comment_captcha_failed ? h($_POST["name"]) : "", "{FORM_EMAIL_VALUE}" => $comment_captcha_failed ? h($_POST["email"]) : "", "{FORM_CONTENT_VALUE}" => $comment_captcha_failed ? h($_POST["content"]) : "", "{FORM_SUBMIT}" => $this->TP_FORM_SUBMIT, "{FORM_SELF}" => h($self), "{FORM_PAGE}" => h($page), "{COMMENTS}" => $this->TP_COMMENTS));
         $items_str = "";
         if ($dir = @opendir($this->comments_dir . $page)) {
             $item_tmpl = "";
             if (preg_match("/\\{item\\}(.*)\\{\\/item\\}/Us", $tmpl, $m)) {
                 $item_tmpl = $m[1];
             }
             $filenames = array();
             while ($filename = @readdir($dir)) {
                 if (preg_match("/([0-9]{8}-[0-9]{4}-[0-9]{2})\\.txt/", $filename, $m)) {
                     $filenames[] = $filename;
                 }
             }
             if ($this->sorting_order == "asc") {
                 sort($filenames);
             } else {
                 if ($this->sorting_order == "desc") {
                     rsort($filenames);
                 }
             }
             $comment_num = 0;
             foreach ($filenames as $filename) {
                 $comment_num++;
                 $file = file_get_contents($this->comments_dir . $page . "/" . $filename);
                 $delimiter = strpos($file, "\n");
                 $meta = substr($file, 0, $delimiter);
                 $content = substr($file, $delimiter + 1);
                 list($ip, $name, $email) = explode("\t", $meta);
                 $processed_content = $this->processComment($content);
                 $items_str .= strtr($item_tmpl, array("{CONTENT}" => $processed_content, "{NAME}" => h($name), "{EMAIL}" => h($email), "{NAME_TO_EMAIL}" => $email == "" ? $name : "<a href=\"mailto:" . h($email) . "\">" . h($name) . "</a>", "{IP}" => $ip, "{DATE}" => rev_time(basename($filename, ".txt")), "{ID}" => basename($filename, ".txt"), "{NUMBER}" => $comment_num, "{DELETE}" => h($this->TP_DELETE), "{DELETE_LINK}" => "{$self}?action=admin-deletecomment&amp;page=" . u($page) . "&amp;filename=" . u($filename), "{DELETE_CONFIRM}" => h($this->TP_DELETE_CONFIRM)));
             }
         }
         $tmpl = str_replace("{NUMBER_OF_COMMENTS}", count($filenames), $tmpl);
         $comments_html = preg_replace("/\\{item\\}.*\\{\\/item\\}/Us", $items_str, $tmpl);
         plugin("commentsTemplate");
         $html = template_replace("plugin:COMMENTS", $comments_html, $html);
         $CON = str_replace("{COMMENTS}", $comments_html, $CON);
     }
     $CON = str_replace("{NO_COMMENTS}", "", $CON);
     $HEAD .= "\n<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS " . h($this->TP_COMMENTS) . "\" href=\"{$this->rss_file}\" />\n";
 }
Esempio n. 16
0
 public function toHtml($_version = 'dashboard')
 {
     $lien_dossier = realpath(dirname(__FILE__) . '/../../flux_rss');
     $li = null;
     //$array_dossier = scandir($lien_dossier);
     $lienfor = $lien_dossier . '/fluxrss_' . $this->getId() . '.json';
     if (file_exists($lienfor)) {
         $fluxRSS = fopen($lienfor, 'r');
         $fluxRSSread = fread($fluxRSS, filesize($lienfor));
         fclose($fluxRSS);
         $fluxRSS = json_decode($fluxRSSread);
         foreach ($fluxRSS as $key => $value) {
             $lien_file_dash_rss = $lien_dossier . '/' . $value . '.json';
             $file_dash_rss = fopen($lien_file_dash_rss, 'r');
             $read_file_dash_rss = fread($file_dash_rss, filesize($lien_file_dash_rss));
             fclose($file_dash_rss);
             $file_dash_rss = null;
             $recuperateur = json_decode($read_file_dash_rss, true);
             $read_file_dash_rss = null;
             $configuration = $this->getconfiguration();
             $theme_voulu = $configuration['theme'];
             if ($theme_voulu == 1) {
                 $theme = 'barre';
             } else {
                 $theme = 'standard';
             }
             if ($theme == 'standard') {
                 $width = '300px';
                 $mini_height = "160px";
                 $mini_widht = "280px";
                 $li .= '<a href="#" class="list-group-item disabled"><img src="http://www.google.com/s2/favicons?domain=' . $recuperateur['lien_rss'] . '" /> ' . $recuperateur['name_rss'] . '</a>';
                 foreach ($recuperateur['contenu'] as $recup) {
                     if (isset($recup['title'])) {
                         $li .= '<a onclick="open_rss' . $this->getId() . '(\'' . $recup['link'] . '\')" class="list-group-item" style="background-color:transparent;cursor:pointer;font-size : 0.9em;">' . htmlentities($recup['title']) . '</a>';
                     } else {
                         foreach ($recup as $recupencore) {
                             if (isset($recupencore['title'])) {
                                 $li .= '<a onclick="open_rss' . $this->getId() . '(\'' . $recupencore['link'] . '\')" class="list-group-item" style="background-color:transparent;cursor:pointer;font-size : 0.9em;">' . $recupencore['title'] . '</a>';
                             }
                         }
                     }
                 }
             } elseif ($theme == 'barre') {
                 $width = '586px';
                 $mini_height = "80px";
                 $mini_widht = "500px";
                 $li .= '<div class="btn-group" style="width:100%;">';
                 $li .= '<button type="button" style="float:left;width:20%;" class="btn btn-danger" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><img src="http://www.google.com/s2/favicons?domain=' . $recuperateur['lien_rss'] . '" /> ' . $recuperateur['name_rss'] . '</button>';
                 //$li .= '<div style="float:left;padding: 6px 12px;" > TEST </div>';
                 $li .= '<button type="button" style="float:left;width:75%;height:32px;" class="btn btn btn-info" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><marquee>';
                 foreach ($recuperateur['contenu'] as $recup) {
                     if (isset($recup['title'])) {
                         $li .= htmlentities($recup['title']) . ' // ';
                     } else {
                         foreach ($recup as $recupencore) {
                             if (isset($recupencore['title'])) {
                                 $li .= $recupencore['title'] . ' // ';
                             }
                         }
                     }
                 }
                 $li .= '</marquee></button>';
                 $li .= '<button type="button" style="float:right;width:5%;" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
                 $li .= '<span class="caret"></span>';
                 $li .= '<span class="sr-only">Toggle Dropdown</span>';
                 $li .= '</button>';
                 $li .= '<ul class="dropdown-menu" style="width:100%;">';
                 foreach ($recuperateur['contenu'] as $recup) {
                     if (isset($recup['title'])) {
                         $li .= '<li><a onclick="open_rss' . $this->getId() . '(\'' . $recup['link'] . '\')" class="list-group-item" style="background-color:transparent;cursor:pointer;font-size : 0.9em;">' . htmlentities($recup['title']) . '</a></li>';
                     } else {
                         foreach ($recup as $recupencore) {
                             if (isset($recupencore['title'])) {
                                 $li .= '<li><a onclick="open_rss' . $this->getId() . '(\'' . $recupencore['link'] . '\')" class="list-group-item" style="background-color:transparent;cursor:pointer;font-size : 0.9em;">' . $recupencore['title'] . '</a></li>';
                             }
                         }
                     }
                 }
                 $li .= '</ul>';
                 $li .= '</div>';
                 $li .= '<br />';
             }
         }
     }
     $_version = jeedom::versionAlias($_version);
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getIsVisible() ? $this->getName() : '<del>' . $this->getName() . '</del>', '#eqLink#' => $this->getLinkToConfiguration(), '#li#' => $li, '#height#' => $this->getDisplay('height', 'auto'), '#width#' => $this->getDisplay('width', $width), '#miniheight#' => $mini_height, '#miniwidth#' => $mini_widht);
     return template_replace($replace, getTemplate('core', $_version, 'eqLogic', 'rss'));
 }
Esempio n. 17
0
 function commentsTemplate()
 {
     global $comments_html;
     $comments_html = template_replace("plugin:RESIZE_TEXTAREA", $this->resize_html, $comments_html);
     $comments_html = template_replace("plugin:TOOLBAR_TEXTAREA", $this->basic_toolbar_html, $comments_html);
 }
Esempio n. 18
0
 public function toHtml($_version = 'dashboard')
 {
     if ($_version == '') {
         throw new Exception(__('La version demandée ne peut pas être vide (mobile, dashboard ou scénario)', __FILE__));
     }
     if (!$this->hasRight('r')) {
         return '';
     }
     $version = jeedom::versionAlias($_version);
     if ($this->getDisplay('hideOn' . $version) == 1) {
         return '';
     }
     $hasOnlyEventOnly = $this->hasOnlyEventOnlyCmd();
     if ($hasOnlyEventOnly) {
         $sql = 'SELECT `value` FROM cache
        WHERE `key`="widgetHtml' . $_version . $this->getId() . '"';
         $result = DB::Prepare($sql, array(), DB::FETCH_TYPE_ROW);
         if ($result['value'] != '') {
             return preg_replace("/" . preg_quote(self::UIDDELIMITER) . "(.*?)" . preg_quote(self::UIDDELIMITER) . "/", self::UIDDELIMITER . mt_rand() . self::UIDDELIMITER, $result['value']);
         }
     }
     $parameters = $this->getDisplay('parameters');
     $cmd_html = '';
     $vcolor = 'cmdColor';
     if ($version == 'mobile') {
         $vcolor = 'mcmdColor';
     }
     $cmdColor = $this->getPrimaryCategory() == '' ? '' : jeedom::getConfiguration('eqLogic:category:' . $this->getPrimaryCategory() . ':' . $vcolor);
     if (is_array($parameters) && isset($parameters['background_cmd_color'])) {
         $cmdColor = $parameters['background_cmd_color'];
     }
     if ($this->getIsEnable()) {
         foreach ($this->getCmd(null, null, true) as $cmd) {
             if ($cmd->getDisplay('hideOn' . $version) == 1) {
                 continue;
             }
             if ($cmd->getDisplay('forceReturnLineBefore', 0) == 1) {
                 $cmd_html .= '<br/>';
             }
             $cmd_html .= $cmd->toHtml($_version, '', $cmdColor);
             if ($cmd->getDisplay('forceReturnLineAfter', 0) == 1) {
                 $cmd_html .= '<br/>';
             }
         }
     }
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getName(), '#eqLink#' => $this->hasRight('w') ? $this->getLinkToConfiguration() : '#', '#category#' => $this->getPrimaryCategory(), '#background_color#' => $this->getBackgroundColor($version), '#cmd#' => $cmd_html, '#style#' => '', '#max_width#' => '650px', '#logicalId#' => $this->getLogicalId(), '#battery#' => $this->getConfiguration('batteryStatus', -2), '#batteryDatetime#' => $this->getConfiguration('batteryStatusDatetime', __('inconnue', __FILE__)), '#batteryType#' => $this->getConfiguration('battery_type', ''), '#object_name#' => '', '#height#' => $this->getDisplay('height', 'auto'), '#width#' => $this->getDisplay('width', 'auto'), '#uid#' => 'eqLogic' . $this->getId() . self::UIDDELIMITER . mt_rand() . self::UIDDELIMITER);
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotShowObjectNameOnView', 0) == 0) {
         $object = $this->getObject();
         $replace['#object_name#'] = is_object($object) ? '(' . $object->getName() . ')' : '';
     }
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotShowNameOnView') == 1) {
         $replace['#name#'] = '';
     }
     if (($_version == 'mobile' || $_version == 'dashboard') && $this->getDisplay('doNotShowNameOnDashboard') == 1) {
         $replace['#name#'] = '';
     }
     if (($_version == 'dview' || $_version == 'mview') && $this->getDisplay('doNotDisplayBatteryLevelOnView') == 1) {
         $replace['#battery#'] = -1;
     }
     if ($_version == 'dashboard' && $this->getDisplay('doNotDisplayBatteryLevelOnDashboard') == 1) {
         $replace['#battery#'] = -1;
     }
     if (is_array($parameters)) {
         foreach ($parameters as $key => $value) {
             $replace['#' . $key . '#'] = $value;
         }
     }
     if (!isset(self::$_templateArray[$version])) {
         self::$_templateArray[$version] = getTemplate('core', $version, 'eqLogic');
     }
     $html = template_replace($replace, self::$_templateArray[$version]);
     if ($hasOnlyEventOnly) {
         cache::set('widgetHtml' . $_version . $this->getId(), $html, 0);
     }
     return $html;
 }
Esempio n. 19
0
 function template()
 {
     global $html, $self;
     $html = template_replace("plugin:LIST_OF_PLUGINS", "<a href=\"{$self}?action=listplugins\" rel=\"nofollow\">List of installed plugins</a>", $html);
 }
Esempio n. 20
0
 function commentsTemplate()
 {
     global $comments_html, $PASSWORD, $HEAD;
     if (!empty($PASSWORD) || $this->permanent && $_COOKIE["LW_CAPTCHA"] == $this->cookie_password) {
         $comments_html = template_replace("plugin:CAPTCHA_QUESTION", "", $comments_html);
         $comments_html = template_replace("plugin:CAPTCHA_INPUT", "", $comments_html);
         return;
     }
     $question_count = $this->questionCount();
     $question_id = rand(1, $question_count);
     $question_text = trim($this->getQuestion($question_id, 1));
     $comments_html = template_replace("plugin:CAPTCHA_QUESTION", '<span id="captcha-question">' . $question_text . "</span>", $comments_html);
     $comments_html = template_replace("plugin:CAPTCHA_INPUT", "<input type=\"hidden\" id=\"captcha-id\" name=\"qid\" value=\"{$question_id}\" /><input type=\"text\" id=\"captcha-input\" name=\"ans\" class=\"input\" value=\"\" />", $comments_html);
     $HEAD .= $this->fillAnswerWithJavascript($question_id);
 }
Esempio n. 21
0
plugin('formatFinished');
// Loading template. If does not exist, use built-in default
$html = file_exists($TEMPLATE) ? file_get_contents(clear_path($TEMPLATE)) : fallback_template();
// including pages in pure HTML
while (preg_match('/{include:([^}]+)}/U', $html, $m)) {
    $inc = str_replace(array('{html}', '{/html}'), '', @file_get_contents("{$PG_DIR}{$m['1']}.txt"));
    $html = str_replace($m[0], $inc, $html);
}
plugin('template');
// plugin templating
$html = preg_replace('/\\{([^}]* )?plugin:.+( [^}]*)?\\}/U', '', $html);
// get rid of absent plugin tags
$tpl_subs = array('HEAD' => $HEAD . ($action ? '<meta name="robots" content="noindex, nofollow"/>' : ''), 'SEARCH_FORM' => '<form action="' . $self . '" method="get"><span><input type="hidden" name="action" value="search"/><input type="submit" style="display:none;"/>', '\\/SEARCH_FORM' => "</span></form>", 'SEARCH_INPUT' => '<input type="text" name="query" value="' . h($query) . '"/>', 'SEARCH_SUBMIT' => "<input class=\"submit\" type=\"submit\" value=\"{$T_SEARCH}\"/>", 'HOME' => "<a href=\"{$self}?page=" . u($START_PAGE) . "\">{$T_HOME}</a>", 'RECENT_CHANGES' => "<a href=\"{$self}?action=recent\">{$T_RECENT_CHANGES}</a>", 'ERROR' => $error, 'HISTORY' => $page ? "<a href=\"{$self}?page=" . u($page) . "&amp;action=history\">{$T_HISTORY}</a>" : "", 'PAGE_TITLE' => h($page == $START_PAGE && $page == $TITLE ? $WIKI_TITLE : $TITLE), 'PAGE_TITLE_HEAD' => h($TITLE), 'PAGE_URL' => u($page), 'EDIT' => !$action ? "<a href=\"{$self}?page=" . u($page) . "&amp;action=edit" . (is_writable("{$PG_DIR}{$page}.txt") ? "\">{$T_EDIT}</a>" : "&amp;showsource=1\">{$T_SHOW_SOURCE}</a>") : "", 'WIKI_TITLE' => h($WIKI_TITLE), 'LAST_CHANGED_TEXT' => $last_changed_ts ? $T_LAST_CHANGED : "", 'LAST_CHANGED' => $last_changed_ts ? date($DATE_FORMAT, $last_changed_ts + $LOCAL_HOUR * 3600) : "", 'CONTENT' => $action != "edit" ? $CON : "", 'TOC' => $TOC, 'SYNTAX' => $action == "edit" || $preview ? "<a href=\"{$SYNTAX_PAGE}\">{$T_SYNTAX}</a>" : "", 'SHOW_PAGE' => $action == "edit" || $preview ? "<a href=\"{$self}?page=" . u($page) . "\">{$T_SHOW_PAGE}</a>" : "", 'COOKIE' => '<a href="' . $self . '?page=' . u($page) . '&amp;action=' . u($action) . '&amp;erasecookie=1">' . $T_ERASE_COOKIE . '</a>', 'CONTENT_FORM' => $CON_FORM_BEGIN, '\\/CONTENT_FORM' => $CON_FORM_END, 'CONTENT_TEXTAREA' => $CON_TEXTAREA, 'CONTENT_SUBMIT' => $CON_SUBMIT, 'CONTENT_PREVIEW' => $CON_PREVIEW, 'RENAME_TEXT' => $RENAME_TEXT, 'RENAME_INPUT' => $RENAME_INPUT, 'EDIT_SUMMARY_TEXT' => $EDIT_SUMMARY_TEXT, 'EDIT_SUMMARY_INPUT' => $EDIT_SUMMARY, 'FORM_PASSWORD' => $FORM_PASSWORD, 'FORM_PASSWORD_INPUT' => $FORM_PASSWORD_INPUT);
foreach ($tpl_subs as $tpl => $rpl) {
    // substituting values
    $html = template_replace($tpl, $rpl, $html);
}
header('Content-type: text/html; charset=UTF-8');
die($html);
// Function library
function h($t)
{
    return htmlspecialchars($t);
}
function u($t)
{
    return urlencode($t);
}
function template_replace($what, $subs, $where)
{
    return preg_replace("/\\{(([^}]*) )?{$what}( ([^}]*))?\\}/U", empty($subs) ? "" : "\${2}" . str_replace("\$", "&#36;", trim($subs)) . "\${4}", $where);
Esempio n. 22
0
 public static function getExpressionOptions($_expression, $_options)
 {
     $startLoadTime = getmicrotime();
     $cmd = cmd::byId(str_replace('#', '', cmd::humanReadableToCmd($_expression)));
     if (is_object($cmd)) {
         $return['html'] = trim($cmd->toHtml('scenario', $_options));
     } else {
         try {
             $return['html'] = getTemplate('core', 'scenario', $_expression . '.default');
             if (is_json($_options)) {
                 $_options = json_decode($_options, true);
             }
             if (is_array($_options) && count($_options) > 0) {
                 foreach ($_options as $key => $value) {
                     $replace['#' . $key . '#'] = $value;
                 }
             }
             if (!isset($replace['#id#'])) {
                 $replace['#id#'] = rand();
             }
             $return['html'] = template_replace(cmd::cmdToHumanReadable($replace), $return['html']);
         } catch (Exception $e) {
         }
     }
     $replace = array('#uid#' => 'exp' . mt_rand());
     $return['html'] = translate::exec(template_replace($replace, $return['html']), 'core/template/scenario/' . $_expression . '.default');
     return $return;
 }
Esempio n. 23
0
 public function toHtml($_version = 'dashboard')
 {
     if ($this->getIsEnable() != 1) {
         return '';
     }
     if (!$this->hasRight('r')) {
         return '';
     }
     $_version = jeedom::versionAlias($_version);
     $background = $this->getBackgroundColor($_version);
     $replace = array('#name#' => $this->getName(), '#id#' => $this->getId(), '#background_color#' => $background, '#eqLink#' => $this->getLinkToConfiguration(), '#height#' => $this->getDisplay('height', 'auto'), '#width#' => $this->getDisplay('width', '200px'), '#temperature_airneufexterieur#' => jeedom::evaluateExpression($this->getConfiguration('temperature_airneufexterieur')), '#temperature_airneufinsuflé#' => jeedom::evaluateExpression($this->getConfiguration('temperature_airneufinsuflé')), '#temperature_airvicie#' => jeedom::evaluateExpression($this->getConfiguration('temperature_airvicie')), '#temperature_airvicierejete#' => jeedom::evaluateExpression($this->getConfiguration('temperature_airvicierejete')));
     $parameters = $this->getDisplay('parameters');
     if (is_array($parameters)) {
         foreach ($parameters as $key => $value) {
             $replace['#' . $key . '#'] = $value;
         }
     }
     $html = template_replace($replace, getTemplate('core', $_version, 'eqLogic', 'vmc'));
     return $html;
 }
Esempio n. 24
0
function lionwiki_show($conf = null, $execute_actions_param = true) {
	global $plugins;
	global $TITLE;
	global $page;
	global $PG_DIR;
	global $DATE_FORMAT;
	global $HIST_DIR;
	global $plugin_ret_diff;
	global $PASSWORD;
	global $sc;
	global $PROTECTED_READ;
	global $content;
	global $error;
	global $action;
	global $html;
	global $preview;
	global $HEAD;
	global $PLUGINS_DIR;
	global $VAR_DIR;
	global $self;
	global $self_form;
	global $CON;
	global $execute_actions;
	global $rightnow;
	global $config;

	$execute_actions = $execute_actions_param;
	
	$is_enterprise = false;
	if (file_exists ("enterprise/include/functions_wiki.php")) {
		require_once ("enterprise/include/functions_wiki.php");
		$is_enterprise = true;
	}
	
	//Default confs
	$wiki_title_conf = 'My new wiki';
	$password_conf = '';
	$template_conf = 'templates/dandelion.html';
	$protected_read_conf = false;
	$no_html_conf = false;
	$start_page_conf = 'Main page';
	$syntax_page_conf = 'http://lionwiki.0o.cz/?page=Syntax+reference';
	$date_format_conf = 'Y/m/d H:i';
	$local_hour_conf = 0;
	$var_dir_conf = 'var/';
	$plugin_dir_conf = 'plugins/';
	$lang_dir_conf = 'lang/';
	$self = basename($_SERVER['PHP_SELF']) . '?';
	$fallback_template = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
	<title>{PAGE_TITLE_HEAD  - }{WIKI_TITLE}</title>
	<style type="text/css">
*{margin:0;padding:0}
body{font-size:12px;line-height:16px;padding:10px 20px 20px 20px}
p{margin:5px}
a{color:#060;text-decoration:none;border-bottom:1px dotted #060}
a.pending{color:#900}
a.external:after{content:"\2197"}
pre{border:1px dotted #ccc;padding:4px;overflow:auto;margin:3px}
img,a img{border:0}
h1,h2,h3,h4,h5,h6{letter-spacing:2px;font-weight:normal;margin:15px 0 15px 0;color:#060}
h1 a:hover,h2 a:hover,h3 a:hover,h4 a:hover,h5 a:hover,h6 a:hover{color:#060}
h1 a{border-bottom:0}
h2 .par-edit,h3 .par-edit,h4 .par-edit,h5 .par-edit,h6 .par-edit{visibility:hidden;font-size:x-small}
h2:hover .par-edit,h3:hover .par-edit,h4:hover .par-edit,h5:hover .par-edit,h6:hover .par-edit{visibility:visible}
hr{margin:10px 0 10px 0;height:1px;overflow:hidden;border:0;background:#060}
ul,ol{padding:5px 0px 5px 20px}
table{text-align:left}
input,select,textarea{border:1px solid #AAA;padding:2px;font-size:12px}
#toc{border:1px dashed #060;margin:5px 0 5px 10px;padding:6px 5px 7px 0;float:right;padding-right:2em;list-style:none}
#toc ul{list-style:none;padding:3px 0 3px 10px}
#toc li{font-size:11px;padding-left:10px}
#diff {padding:1em; white-space: pre-wrap; width: 97%;}
#diff ins{color:green;font-weight:bold}
#diff del{color:red;text-decoration:line-through}
#diff .orig{color:#666;font-size:90%}
/* Plugins */
.tagList{padding:0.2em 0.4em 0.2em 0.4em;margin-top:0.5em;border:1px dashed #060;clear:right}
.tagCloud{float:right;width:200px;padding:0.5em;margin:1em;border:1px dashed #060;clear:right}
.pageVersionsList{letter-spacing:0;font-variant:normal;font-size:12px}
.resizeTextarea a{border-bottom:none}

	</style>
	{HEAD}
</head>
<body>
<table width="100%" cellpadding="4">
<tr>
	<td colspan="2">{HOME} {RECENT_CHANGES}</td>
	<td style="text-align:right">{EDIT} {SYNTAX} {HISTORY}</td>
</tr>
<tr><th colspan="3"><hr/><h1 id="page-title">{PAGE_TITLE} {<span class="pageVersionsList">( plugin:VERSIONS_LIST )</span>}</h1></th></tr>
<tr>
	<td colspan="3">
		{<div style="color:#F25A5A;font-weight:bold;"> ERROR </div>}
		{CONTENT} {plugin:TAG_LIST}
		{CONTENT_FORM} {RENAME_TEXT} {RENAME_INPUT <br/><br/>} {CONTENT_TEXTAREA}
		<p style="float:right;margin:6px">{FORM_PASSWORD} {FORM_PASSWORD_INPUT} {plugin:CAPTCHA_QUESTION} {plugin:CAPTCHA_INPUT}
		{EDIT_SUMMARY_TEXT} {EDIT_SUMMARY_INPUT} {CONTENT_SUBMIT} {CONTENT_PREVIEW}</p>{/CONTENT_FORM}
	</td>
</tr>
<tr><td colspan="3"><hr/></td></tr>
<tr>
	<td><div>{SEARCH_FORM}{SEARCH_INPUT}{SEARCH_SUBMIT}{/SEARCH_FORM}</div></td>
	<td>{LAST_CHANGED_TEXT}: {LAST_CHANGED} {COOKIE}</td>
	<td style="text-align:right">{EDIT} {SYNTAX} {HISTORY}</td>
</tr>
</table>
</body>
</html>';
	
	if ($conf != null) {
		if (isset($conf['wiki_title'])) $wiki_title_conf = $conf['wiki_title'];
		if (isset($conf['password'])) $password_conf = $conf['password'];
		if (isset($conf['template'])) $template_conf = $conf['template'];
		if (isset($conf['protected_read'])) $protected_read_conf = $conf['protected_read'];
		if (isset($conf['no_html'])) $no_html_conf = $conf['no_html'];
		if (isset($conf['start_page'])) $start_page_conf = $conf['start_page'];
		if (isset($conf['syntax_page'])) $syntax_page_conf = $conf['syntax_page'];
		if (isset($conf['date_format'])) $date_format_conf = $conf['date_format'];
		if (isset($conf['local_hour'])) $local_hour_conf = $conf['local_hour'];
		if (isset($conf['var_dir'])) $var_dir_conf = $conf['var_dir'];
		if (isset($conf['plugin_dir'])) $plugin_dir_conf = $conf['plugin_dir'];
		if (isset($conf['lang_dir'])) $lang_dir_conf = $conf['lang_dir'];
		if (isset($conf['self'])) $self = $conf['self'];
		if (isset($conf['fallback_template'])) $fallback_template = $conf['fallback_template'];
	}
	else {
		loadConfig();
	}
	
	//Delete the last character, it is ? or & normality.
	$self_form = substr_replace($self, '', -1);
	
	/*
	 * Disabled for avoid lost the var $action or $page for example
	foreach ($_REQUEST as $k => $v)
		unset($$k); // register_globals = off
	*/ 
	
	// SETTINGS - default settings, can be overridden in config.php
	$WIKI_TITLE = $wiki_title_conf; // name of the site
	$PASSWORD = $password_conf; // SHA1 hash
	
	$TEMPLATE = $template_conf; // presentation template
	$PROTECTED_READ = $protected_read_conf; // if true, you need to fill password for reading pages too
	$NO_HTML = 0; //$no_html_conf; // XSS protection
	
	$START_PAGE = $start_page_conf; // Which page should be default (start page)?
	$SYNTAX_PAGE = $syntax_page_conf;
	
	$DATE_FORMAT = $date_format_conf;
	$LOCAL_HOUR = $local_hour_conf;
	
	@error_reporting(E_ERROR | E_WARNING | E_PARSE);
	@ini_set('default_charset', 'UTF-8');
	set_magic_quotes_runtime(0);
	umask(0);
	
	if (get_magic_quotes_gpc()) // magic_quotes_gpc can't be turned off
		for ($i = 0, $_SG = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST), $c = count($_SG); $i < $c; ++$i)
			$_SG[$i] = array_map('stripslashes', $_SG[$i]);
	
	$REAL_PATH = realpath(dirname(__FILE__)) . '/';
	$VAR_DIR = $var_dir_conf;
	$PG_DIR = $VAR_DIR . 'pages/';
	$HIST_DIR = $VAR_DIR . 'history/';
	$PLUGINS_DIR = $plugin_dir_conf;
	$PLUGINS_DATA_DIR = $VAR_DIR.'plugins/';
	$LANG_DIR = $lang_dir_conf;
	
	
	// default translation
	$T_HOME = 'Main page';
	$T_SYNTAX = 'Syntax';
	$T_DONE = 'Save changes';
	$T_DISCARD_CHANGES = 'Discard changes';
	$T_PREVIEW = 'Preview';
	$T_SEARCH = 'Search';
	$T_SEARCH_RESULTS = 'Wiki search results';
	$T_LIST_OF_ALL_PAGES = 'List of all pages';
	$T_RECENT_CHANGES = 'Recent changes';
	$T_LAST_CHANGED = 'Last changed';
	$T_HISTORY = 'History';
	$T_RESTORE = 'Restore';
	$T_REV_DIFF = '<b>Difference between revisions from {REVISION1} and {REVISION2}.</b>';
	$T_REVISION = "'''This revision is from {TIME}. You can {RESTORE} it.'''\n\n";
	$T_PASSWORD = '******';
	$T_EDIT = 'Edit';
	$T_EDIT_SUMMARY = 'Summary of changes';
	$T_EDIT_CONFLICT = 'Edit conflict: somebody saved this page after you started editing. See last {DIFF} before saving your changes.';
	$T_SHOW_SOURCE = 'Show source';
	$T_SHOW_PAGE = 'Show page';
	$T_ERASE_COOKIE = 'Erase cookies';
	$T_MOVE_TEXT = 'New name';
	$T_DIFF = 'diff';
	$T_CREATE_PAGE = 'Create page';
	$T_PROTECTED_READ = 'You need to enter password to view content of site: ';
	$T_WRONG_PASSWORD = '******';
	
	if ($_GET['lang']) {
		$LANG = clear_path($_GET['lang']);
		setcookie('LW_LANG', $LANG, time() + 365 * 86400);
	}
	elseif ($_COOKIE['LW_LANG'])
		$LANG = clear_path($_COOKIE['LW_LANG']);
	else
		list($LANG) = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
	
	if ((@include("$LANG_DIR$LANG.php")) === false && (@include($LANG_DIR . substr($LANG, 0, 2) . '.php')) === false)
		$LANG = 'en';
	
	
	// Creating essential directories if they don't exist
	if (!file_exists($VAR_DIR) && !mkdir(rtrim($VAR_DIR, "/")))
		die("Can't create directory $VAR_DIR. Please create $VAR_DIR with 0777 rights.");
	else
		foreach (array($PG_DIR, $HIST_DIR, $PLUGINS_DATA_DIR) as $DIR)
			if (@mkdir(rtrim($DIR, '/'), 0777)) {
				$f = fopen($DIR . ".htaccess", "w"); fwrite($f, "deny from all"); fclose($f);
			}
	
	
	if ($_GET['erasecookie']) // remove cookie without reloading
		foreach ($_COOKIE as $k => $v)
			if (substr($k, 0, 3) == 'LW_') {
				setcookie($k);
				unset($_COOKIE[$k]);
			}
	
	//Load Plugins
	for ($plugins = array(), $dir = @opendir($PLUGINS_DIR); $dir && $f = readdir($dir);) // load plugins
		if (preg_match('/wkp_(.+)\.php$/', $f, $m) > 0) {
			require_once $PLUGINS_DIR . $f;
			$plugins[$m[1]] = new $m[1]();
			
			if (isset($$m[1]))
				foreach ($$m[1] as $name => $value)
					$plugins[$m[1]]->$name = $value;
		}
	
	plugin('pluginsLoaded');
	
	foreach (array('action', 'content', 'error', 'esum', 'f1', 'f2',
		'last_changed', 'moveto', 'page', 'par', 'preview', 'query', 'restore',
		'sc', 'showsource', 'time') as $req)
		$$req = $_REQUEST[$req]; // export request variables to global namespace
	
	if (empty($page)) {
		$page = $start_page_conf;
	}
	
	$TITLE = $page = clear_path($page);
	$moveto = clear_path($moveto);
	$f1 = clear_path($f1);
	$f2 = clear_path($f2);
	$CON = $content;
	
	plugin('actionBegin');
	
	if (!$action) {

		if (!$page) {

			error_show_lionwiki("Location:$self" . "page=" . u($START_PAGE));
		}
		elseif (file_exists("$PG_DIR$page.$LANG.txt")) { // language variant

			error_show_lionwiki("Location:$self" . "page=" . u("$page.$LANG"));
		} elseif (!file_exists("$PG_DIR$page.txt")) {

			$action = 'edit'; // create page if it doesn't exist
			
			if (check_no_new_page()) {
				if (!plugin('check_no_new_page')) {
					$action = 'view-html';
				}
				else {
					$action = 'view-html';
				}
			}
		}
	}
	
	//Disable the action
	if (!$execute_actions) {
		$action = '';
	}

	//Check the create new page
	if ($action == 'edit') {
		if (!file_exists("$PG_DIR$page.txt")) {
			if (check_no_new_page()) {
				if (!plugin('show_message_no_new_page')) {
					$action = 'view-html';
				}
				else {
					$action = 'view-html';
				}
			}
		}
	}
	
	if (check_no_read()) {
		if (!plugin('show_message_no_read')) {
			$CON = "<form action=\"$self_form" . "page=".u($page)."\" method=\"post\"><p>$T_PROTECTED_READ <input type=\"password\" name=\"sc\"/> <input class=\"submit\" type=\"submit\"/></p></form>";
			$action = 'view-html';
		}
		else {
			$action = 'view-html';
		}
	}
	else {
		if ($restore || $action == 'rev') { // Show old revision
			$CON = @file_get_contents("$HIST_DIR$page/$f1");
			
			if ($action == 'rev') {
				$rev_restore = "[$T_RESTORE|./$self" . "page=".u($page)."&amp;action=edit&amp;f1=$f1&amp;restore=1]";
				$CON = strtr($T_REVISION, array('{TIME}' => rev_time($f1), '{RESTORE}' => $rev_restore)) . $CON;
				$action = '';
			}
		}
		else if ($page) { // Load the page
			$last_changed_ts = @filemtime("$PG_DIR$page.txt");
			
			if (!$action || $action == 'edit') {
				$CON = @file_get_contents("$PG_DIR$page.txt");
				$CON = $par ? get_paragraph($CON, $par) : $CON;
				
				if (!$action && substr($CON, 0, 10) == '{redirect:' && $_REQUEST['redirect'] != 'no')
					error_show_lionwiki("Location:$self" . "page=".u(substr($CON, 10, strpos($CON, '}') - 10)));
			}
		}
	}
	
	if ($action == 'save' && check_no_save()) {
		if (!plugin('show_message_no_save')) {
			$action = 'view-html';
		}
		else {
			$action = 'view-html';
		}
	}
	else {
		$rightnow = date('Ymd-Hi-s', time() + $LOCAL_HOUR * 3600);
		
		if ($action == 'save' && !$preview && authentified()) { // do we have page to save?
			if (!trim($content) && !$par) // delete empty page
				@unlink("$PG_DIR$page.txt");
			elseif ($last_changed < @filemtime("$PG_DIR$page.txt")) {
				$action = 'edit';
				$error = str_replace('{DIFF}', "<a href=\"$self" . "page=".u($page)."&amp;action=diff\">$T_DIFF</a>", $T_EDIT_CONFLICT);
			}
			elseif (!plugin('writingPage')) { // are plugins OK with page? (e.g. checking for spam)
				if ($par) {
					$c = @file_get_contents("$PG_DIR$page.txt");
					$content = str_replace(get_paragraph($c, $par), $content, $c);
				}
				
				if (!$file = @fopen("$PG_DIR$page.txt", 'w'))
					die("Could not write page $PG_DIR$page.txt!");
				
				fwrite($file, $content); fclose($file);
				
				// Backup old revision
				@mkdir($HIST_DIR.$page, 0777); // Create directory if does not exist
				
				if (!$bak = @fopen("$HIST_DIR$page/$rightnow.bak", 'w'))
					die("Could not write to $HIST_DIR$page!");
				
				fwrite($bak, $content); fclose($bak);
				
				$es = fopen("$HIST_DIR$page/meta.dat", 'ab');
				
				fwrite($es, '!' . $rightnow .
					str_pad($_SERVER['REMOTE_ADDR'], 16, ' ', STR_PAD_LEFT) .
					str_pad(filesize("$PG_DIR$page.txt"), 11, ' ', STR_PAD_LEFT) . ' ' .
					str_pad(substr($esum, 0, 128), 128 + 2)) . "\n";
				
				fclose($es);
				
				if ($moveto != $page && $moveto)
					if (file_exists("$PG_DIR$moveto.txt"))
						die('Error: target filename already exists. Page was not moved.');
					elseif (!rename("$PG_DIR$page.txt", "$PG_DIR$moveto.txt"))
						die('Unknown error! Page was not moved.');
					elseif (!rename($HIST_DIR.$page, $HIST_DIR.$moveto)) {
						rename("$PG_DIR$moveto.txt", "$PG_DIR$page.txt"); // revert previous change
						die('Unknown error2! Page was not moved.');
					}
					else
						$page = $moveto;
				
				if (!plugin('pageWritten')) {
					error_show_lionwiki("Location:$self" . 
						"page=" . u($page) . '&redirect=no' . 
						($par ? "&par=$par" : '') . ($_REQUEST['ajax'] ? '&ajax=1' : ''));
				}
				else {
					$action = ''; // display content ...
				}
				
				$par = 1; //reset counter
				
				//Show all page not only the section.
				$CON = $content;
			}
			else {// there's some problem with page, give user a chance to fix it
				$action = 'edit';
			}
		}
		elseif ($action == 'save' && !$preview) { // wrong password, give user another chance
			$error = $T_WRONG_PASSWORD;
			$action = 'edit';
		}
	}
	
	if ($action == 'edit' || $preview) {

		$has_permission = true;
		if ($is_enterprise) {
			$has_permission = wiki_get_write_acl($config['id_user'], $page);

		}
		if ($has_permission) {
			$CON_FORM_BEGIN = "<form action=\"$self_form\" method=\"post\"><input type=\"hidden\" name=\"action\" value=\"save\"/><input type=\"hidden\" name=\"last_changed\" value=\"$last_changed_ts\"/><input type=\"hidden\" name=\"showsource\" value=\"$showsource\"/><input type=\"hidden\" name=\"par\" value=\"".h($par)."\"/><input type=\"hidden\" name=\"page\" value=\"".h($page)."\"/>";
			$CON_FORM_END = '</form>';
			$CON_TEXTAREA = '<textarea class="contentTextarea" name="content" rows="27">'.h($CON).'</textarea>';
			$CON_PREVIEW = '<input class="submit" type="submit" name="preview" value="'.$T_PREVIEW.'"/>';
			
			if (!$showsource) {
				$CON_SUBMIT = '<input class="submit" type="submit" value="'.$T_DONE.'"/>';
				$EDIT_SUMMARY_TEXT = $T_EDIT_SUMMARY;
				$EDIT_SUMMARY = '<input type="text" name="esum" value="'.h($esum).'"/>';
				
				if (!authentified()) { // if not logged on, require password
					$FORM_PASSWORD = $T_PASSWORD;
					$FORM_PASSWORD_INPUT = '<input type="password" name="sc"/>';
				}
				
				if (!$par) {
					$RENAME_TEXT = $T_MOVE_TEXT;
					$RENAME_INPUT = '<input type="text" name="moveto" value="'.h($page).'"/>';
				}
			}
			
			if ($preview)
				$TITLE = "$T_PREVIEW: $page";
		} else {
			include "general/noaccess.php";
			exit;
		}
	}
	elseif ($action == 'history') { // show whole history of page
		for ($files = array(), $dir = @opendir("$HIST_DIR$page/"); $f = @readdir($dir);)
			if (substr($f, -4) == '.bak')
				$files[] = $f;
		
		rsort($files);
		$CON = '<form action="'.$self_form.'" method="post"><input type="hidden" name="action" value="diff"/><input type="hidden" name="page" value="'.h($page).'"/><input type="submit" class="submit" value="'.$T_DIFF.'"/><br/>';
		$meta = @fopen("$HIST_DIR$page/meta.dat", "rb");
	
		for ($i = 0, $mi = 1, $c = count($files); $i < $c; $i++) {
			if (($m = meta_getline($meta, $mi)) && !strcmp(basename($files[$i], ".bak"), $m[0]))
				$mi++;
			
			global $return_loadMetadata;
			$return_loadMetadata = '';
			plugin('loadMetadata',$page, $m);
			
			//Replace IP for the return of loadMetaData
			if (!empty($return_loadMetadata)) {
				$m[1] = $return_loadMetadata;
			}
			
			$CON .= '<input type="radio" name="f1" value="'.h($files[$i]).'"/><input type="radio" name="f2" value="'.h($files[$i]).'"/>';
			$CON .= "<a href=\"$self" . "page=".u($page)."&amp;action=rev&amp;f1=".$files[$i]."\">".rev_time($files[$i])."</a> - ($m[2] B) $m[1] <i>".h($m[3])."</i><br/>";
		}
		
		$CON .= '</form>';
	}
	elseif ($action == 'diff') {
		if (!$f1 && $dir = @opendir("$HIST_DIR$page/")) { // diff is made on two last revisions
			while ($f = @readdir($dir))
				if (substr($f, -4) == '.bak')
					$files[] = $f;
			
			$i = count($files);
			rsort($files);
			$f1=$files[$i - 1];
			$f2=$files[$i - 2];
			error_show_lionwiki("Location:$self" . "action=diff&page=".u($page)."&f1=$files[0]&f2=$files[1]");
		}
		
		$r1 = "<a href=\"$self" . "page=".u($page)."&amp;action=rev&amp;f1=$f1\">".rev_time($f1)."</a>";
		$r2 = "<a href=\"$self" . "page=".u($page)."&amp;action=rev&amp;f1=$f2\">".rev_time($f2)."</a>";
		
		$CON = str_replace(array("{REVISION1}", "{REVISION2}"), array($r1, $r2), $T_REV_DIFF);
		$CON .= diff($f1, $f2);
	}
	elseif ($action == 'search') {
		for ($files = array(), $dir = opendir($PG_DIR); $f = readdir($dir);) {
			if (substr($f, -4) == '.txt' && ($c = @file_get_contents($PG_DIR . $f)) !== false) {
				if (!$query || stristr($f . $c, $query) !== false)
					$files[] = substr($f, 0, -4);
			}
		}
		
		sort($files);
		
		foreach ($files as $f)
			$list .= "<li><a href=\"$self" . "page=".u($f).'&amp;redirect=no">'.h($f)."</a></li>";
		
		$CON = "<ul>$list</ul>";
		
		if ($query && !file_exists("$PG_DIR$query.txt")) // offer to create the page
			$CON = "<p><i><a href=\"$self" . "action=edit&amp;page=".u($query)."\">$T_CREATE_PAGE ".h($query)."</a>.</i></p>".$CON;
		
		$TITLE = (!$query ? $T_LIST_OF_ALL_PAGES : "$T_SEARCH_RESULTS $query") . " (".count($files).")";
	}
	elseif ($action == 'recent') { // recent changes
		for ($files = array(), $dir = opendir($PG_DIR); $f = readdir($dir);)
			if (substr($f, -4) == '.txt')
				$files[substr($f, 0, -4)] = filemtime($PG_DIR . $f);
		
		arsort($files);
		
		foreach (array_slice($files, 0, 100) as $f => $ts) { // just first 100 files
			$dir_name = basename($f, '.txt');
			if ($meta = @fopen($HIST_DIR . $dir_name . '/meta.dat', 'r')) {
				$m = meta_getline($meta, 1);
				fclose($meta);
			}
			global $return_loadMetadata;
			$return_loadMetadata = '';
			plugin('loadMetadata',$dir_name, $m);
			
			//Replace IP for the return of loadMetaData
			if (!empty($return_loadMetadata)) {
				$m[1] = $return_loadMetadata;
			}
			
			$recent .= "<tr><td class=\"rc-diff\"><a href=\"$self" . "page=".u($f)."&amp;action=diff\">$T_DIFF</a></td><td class=\"rc-date\" nowrap>".date($DATE_FORMAT, $ts + $LOCAL_HOUR * 3600)."</td><td class=\"rc-ip\">$m[1]</td><td class=\"rc-page\"><a href=\"$self" . "page=".u($f)."&amp;redirect=no\">".h($f)."</a> <span class=\"rc-size\">($m[2] B)</span><i class=\"rc-esum\"> ".h($m[3])."</i></td></tr>";
		}
		
		$CON = "<table>$recent</table>";
		$TITLE = $T_RECENT_CHANGES;
	}
	
	elseif ($action == 'read_acl') { 

		$page_acl = get_parameter('page');

		$delete_acl_read = get_parameter('delete_acl_read', 0);
		$add_acl_read = get_parameter('add_acl_read', 0);
		
		$acl = '';
		
		if ($add_acl_read) {

			$new_user = get_parameter('new_user');
			
			$values = array();
			
			$exists = wiki_exists_page($page_acl);
		
			if ($exists) {

				$update = wiki_update_wiki($page_acl, $new_user, 'read');
				if ($update === false) {
					$acl .= "<h4>Error updating user</h4>";
				} else {
					$acl .= "<h4>User succesfully added</h4>";
				}
			} else {

				$insert = wiki_insert_wiki($page_acl, $new_user, 'read');
				if ($insert === false) {
					$acl .= "<h4>Error adding user</h4>";
				} else {
					$acl .= "<h4>User succesfully created</h4>";
				}
			}
		}
		
		if ($delete_acl_read) {
			
			$id_user = get_parameter('id_user');
	
			$result = wiki_delete_acl($id_user, $page_acl, 'read');
			
			if ($result === false) {
				$acl .= "<h4>Error deleting user</h4>";
			} else {
				$acl .= "<h4>User succesfully deleted</h4>";
			}
		}	
		
		$acl .= "<h3>$page_acl".print_help_tip (__("If a content has any users in its reading list, it will be accessible to all people. When we add an user to the access lists, only those users will have reading or writing permissions."), true)."</h3>";
		include_once('include/functions_db.php');
		include_once('include/functions_html.php');
		include_once('include/functions_user.php');
		
		$acls = wiki_get_acls ($page_acl);
		
		$table->id = 'acl_list';
		$table->class = 'listing';
		$table->width = '98%';
		$table->data = array ();
		$table->head = array ();
		
		$table->size[1] = '80px';
		
		$table->head[0] = __('Read');
		$table->head[1] = __('Operation');
			
		if ($acls === false) {
			$acl .= "<h4>No acls</h4>";
		} 
			
		$read = $acls['read_page'];
		
		if (!empty($read)) {
			$users_read = explode(',', $read);
			
			foreach ($users_read as $key=>$user) {
				$data = array();
				$data[0] = $user;
				$data[1] = '<a href="index.php?sec=wiki&
							sec2=operation/wiki/wiki&action=read_acl&
							delete_acl_read=1&page='.$page_acl.'&id_user='******'"
							onClick="if (!confirm(\''.__('Are you sure?').'\'))
							return false;">
							<img src="images/cross.png" /></a>';
				array_push ($table->data, $data);
			}
		}
		
		$data = array();
		
		$params_assigned['input_id'] = 'text-new_user';
		$params_assigned['input_name'] = 'new_user';
		$params_assigned['input_value'] = '';
		$params_assigned['title'] = 'New user';
		$params_assigned['return'] = true;

		$url = "index.php?sec=wiki&sec2=operation/wiki/wiki&action=read_acl&add_acl_read=1&page=$page_acl";

		$data[0] = "<form name=adduser method=post action='" . $url . "'>";
		$data[0] .= user_print_autocomplete_input($params_assigned);
		$data[1] = print_input_image("add_user", "images/add.png", 1, '', true);
		$data[1] .= "</form>";
						
		array_push ($table->data, $data);
		
		$acl .= print_table($table, true);
			

		$CON = "<table>$acl</table>";
		$TITLE = "READ ACL";
	}
	elseif ($action == 'write_acl') { 

		$page_acl = get_parameter('page');

		$delete_acl_write = get_parameter('delete_acl_write', 0);
		$add_acl_write = get_parameter('add_acl_write', 0);

		$new_user = get_parameter('new_user', '');
		
		$acl = '';
		
		if ($add_acl_write) {

			$new_user = get_parameter('new_user');
			
			$values = array();
			
			$exists = wiki_exists_page($page_acl);
		
			if ($exists) {

				$update = wiki_update_wiki($page_acl, $new_user, 'write');
				
				if ($update === false) {
					$acl .= "<h4>Error updating user</h4>";
				} else {
					$acl .= "<h4>User succesfully added</h4>";
				}
			} else {

				$insert = wiki_insert_wiki($page_acl, $new_user, 'write');
				
				if ($insert === false) {
					$acl .= "<h4>Error adding user</h4>";
				} else {
					$acl .= "<h4>User succesfully created</h4>";
				}
			}
		}
		
		if ($delete_acl_write) {
			
			$id_user = get_parameter('id_user');

			$result = wiki_delete_acl($id_user, $page_acl, 'write');
			
			if ($result === false) {
				$acl .= "<h4>Error deleting user</h4>";
			} else {
				$acl .= "<h4>User succesfully deleted</h4>";
			}
		}	
		
		$acl .= "<h3>$page_acl".print_help_tip (__("If a content has any users in its writing list, it will be accessible to all people. When we add an user to the access lists, only those users will have reading or writing permissions."), true)."</h3>";
		include_once('include/functions_db.php');
		include_once('include/functions_html.php');
		include_once('include/functions_user.php');
		
		$acls = wiki_get_acls ($page_acl);
		
		$table->id = 'acl_list';
		$table->class = 'listing';
		$table->width = '98%';
		$table->data = array ();
		$table->head = array ();
		
		$table->size[1] = '80px';
		
		$table->head[0] = __('Write');
		$table->head[1] = __('Operation');
			
		if ($acls === false) {
			$acl .= "<h4>No acls</h4>";
		} 
			
		$read = $acls['write_page'];
		
		if (!empty($read)) {
			$users_read = explode(',', $read);
			
			foreach ($users_read as $key=>$user) {
				$data = array();
				$data[0] = $user;
				$data[1] = '<a href="index.php?sec=wiki&
							sec2=operation/wiki/wiki&action=write_acl&
							delete_acl_write=1&page='.$page_acl.'&id_user='******'"
							onClick="if (!confirm(\''.__('Are you sure?').'\'))
							return false;">
							<img src="images/cross.png" /></a>';
				array_push ($table->data, $data);
			}
		}

		$data = array();
		$params_assigned['input_id'] = 'text-new_user';
		$params_assigned['input_name'] = 'new_user';
		$params_assigned['input_value'] = '';
		$params_assigned['title'] = 'New user';
		$params_assigned['return'] = true;

		$url = "index.php?sec=wiki&sec2=operation/wiki/wiki&action=write_acl&add_acl_write=1&page=$page_acl";

		$data[0] = "<form id='form-adduser' name=adduser method=post action='" . $url . "'>";
		$data[0] .= user_print_autocomplete_input($params_assigned);
		$data[1] = print_input_image("add_user", "images/add.png", 1, '', true);
		$data[1] .= "</form>";
						
		array_push ($table->data, $data);
		
		$acl .= print_table($table, true);
			

		$CON = "<table>$acl</table>";
		$TITLE = "WRITE ACL";
	}
	else {
		if (!plugin('check_no_action', $action)) { //Check to block or not a action
			plugin('action', $action);
		}
		else {
			if (!plugin('show_message_no_save')) {
				$action = 'view-html';
			}
			else {
				$action = 'view-html';
			}
		}
	}
	
	if (!$action || $action == 'save' || $preview) { // page parsing
		if (preg_match("/(?<!\^)\{title:([^}\n]*)\}/U", $CON, $m)) { // Change page title
			$TITLE = $m[1];
			$CON = str_replace($m[0], "", $CON);
		}
		
		// subpages
		while (preg_match('/(?<!\^){include:([^}]+)}/Um', $CON, $m))
			if (!strcmp($m[1], $page)) // limited recursion protection
				$CON = str_replace($m[0], "'''Warning: subpage recursion!'''", $CON);
			elseif (file_exists("$PG_DIR$m[1].txt"))
				$CON = str_replace($m[0], file_get_contents("$PG_DIR$m[1].txt"), $CON);
			else
				$CON = str_replace($m[0], "'''Warning: subpage $m[1] was not found!'''", $CON);
		
		plugin('subPagesLoaded');
		
		// save content not intended for substitutions ({html} tag)
		if (!$NO_HTML) { // XSS protection
			preg_match_all("/(?<!\^)\{html\}(.+)\{\/html\}/Ums", $CON, $htmlcodes, PREG_PATTERN_ORDER);
			$CON = preg_replace("/(?<!\^)\{html\}.+\{\/html\}/Ums", "{HTML}", $CON);
		}
		
		$CON = preg_replace("/(?<!\^)<!--.*-->/U", "", $CON); // internal comments
		$CON = preg_replace("/\^(.)/e", "'&#'.ord('$1').';'", $CON);
		$CON = str_replace(array("<", "&"), array("&lt;", "&amp;"), $CON);
		$CON = preg_replace("/&amp;([a-z]+;|\#[0-9]+;)/U", "&$1", $CON); // keep HTML entities
		$CON = preg_replace("/(\r\n|\r)/", "\n", $CON); // unifying newlines to Unix ones
		
		preg_match_all("/{{(.+)}}/Ums", $CON, $codes, PREG_PATTERN_ORDER);
		$CON = preg_replace("/{{(.+)}}/Ums", "<pre>{CODE}</pre>", $CON);
		
		// spans
		preg_match_all("/\{([\.#][^\s\"\}]*)(\s([^\}\"]*))?\}/m", $CON, $spans, PREG_SET_ORDER);
		
		foreach ($spans as $m) {
			$class = $id = '';
			$parts = preg_split('/([\.#])/', $m[1], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
			
			for ($i = 0, $c = count($parts); $c > 1 && $i < $c; $i += 2)
				if ($parts[$i] == '.')
					$class .= $parts[$i + 1] . ' ';
				else
					$id = $parts[$i + 1];
			
			$CON = str_replace($m[0], '<span'.($id ? " id=\"$id\"" : '').($class ? " class=\"$class\"" : '').($m[3] ? " style=\"$m[3]\"" : '').'>', $CON);
		}
		
		$CON = str_replace('{/}', '</span>', $CON);
		
		plugin('formatBegin');
		
		$CON = strtr($CON, array('&lt;-->' => '&harr;', '-->' => '&rarr;', '&lt;--' => '&larr;', "(c)" => '&copy;', "(r)" => '&reg;'));
		$CON = preg_replace("/\{small\}(.*)\{\/small\}/U", "<small>$1</small>", $CON); // small
		$CON = preg_replace("/\{su([bp])\}(.*)\{\/su([bp])\}/U", "<su$1>$2</su$3>", $CON); // sup and sub
		
		$CON = preg_replace("/^([^!\*#\n][^\n]+)$/Um", '<p>$1</p>', $CON); // paragraphs
		
		// images
		preg_match_all("#\[((https?://|\./)[^|\]]+\.(jpeg|jpg|gif|png))(\|[^\]]+)?\]#", $CON, $imgs, PREG_SET_ORDER);
		
		foreach ($imgs as $img) {
			$link = $i_attr = $a_attr = $center = $tag = "";
			
			preg_match_all("/\|([^\]\|=]+)(=([^\]\|\"]+))?(?=[\]\|])/", $img[0], $options, PREG_SET_ORDER);
			
			foreach ($options as $o)
				if ($o[1] == 'center') $center = true;
				elseif ($o[1] == 'right' || $o[1] == 'left') $i_attr .= " style=\"float:$o[1]\"";
				elseif ($o[1] == 'link') $link = (substr($o[3], 0, 4) == "http" || substr($o[3], 0, 2) == "./") ? $o[3] : $self . "page=" . u($o[3]);
				elseif ($o[1] == 'alt') $i_attr .= " alt=\"$o[3]\"";
				elseif ($o[1] == 'title') $a_attr .= " title=\"$o[3]\"";
			
			$tag = "<img src=\"$img[1]\"$i_attr/>";
			
			if ($link) $tag = "<a href=\"$link\"$a_attr>$tag</a>";
			if ($center) $tag = "<div style=\"text-align:center\">$tag</div>";
			
			$CON = str_replace($img[0], $tag, $CON);
		}
		
		$CON = preg_replace('#([0-9a-zA-Z\./~\-_]+@[0-9a-z/~\-_]+\.[0-9a-z\./~\-_]+)#i', '<a href="mailto:$0">$0</a>', $CON); // mail recognition
		
		// links
		$CON = preg_replace("#\[([^\]\|]+)\|(\./([^\]]+)|(https?://[^\]]+))\]#U", '<a href="$2" class="external">$1</a>', $CON);
		$CON = preg_replace("#(?<!\")https?://[0-9a-zA-Z\.\#/~\-_%=\?\&,\+\:@;!\(\)\*\$']*#i", '<a href="$0" class="external">$0</a>', $CON);
		
		preg_match_all("/\[(?:([^|\]]+)\|)?([^\]#]+)(?:#([^\]]+))?\]/", $CON, $matches, PREG_SET_ORDER); // matching Wiki links
		
		foreach ($matches as $m) {
			$m[1] = $m[1] ? $m[1] : $m[2]; // is page label same as its name?
			$m[3] = $m[3] ? '#'.u(preg_replace('/[^\da-z]/i', '_', $m[3])) : ''; // anchor
			
			$attr = file_exists("$PG_DIR$m[2].txt") ? $m[3] : '&amp;action=edit" class="pending';
			$CON = str_replace($m[0], '<a href="'.$self.'page='.u($m[2]).$attr.'">'.$m[1].'</a>', $CON);
		}
		
		for ($i = 10; $i >= 1; $i--) { // Lists, ordered, unordered
			$CON = preg_replace('/^'.str_repeat('\*', $i)."(.*)(\n?)/m", str_repeat('<ul>', $i).'<li>$1</li>'.str_repeat('</ul>', $i).'$2', $CON);
			$CON = preg_replace('/^'.str_repeat('\#', $i)."(.*)(\n?)/m", str_repeat('<ol>', $i).'<li>$1</li>'.str_repeat('</ol>', $i).'$2', $CON);
			$CON = preg_replace("#(</ol>\n?<ol>|</ul>\n?<ul>)#", '', $CON);
		}
		
		// headings
		preg_match_all('/^(!+)(.*)$/m', $CON, $matches, PREG_SET_ORDER);
		$stack = array();
		
		for ($h_id = max($par, 1), $i = 0, $c = count($matches); $i < $c && $m = $matches[$i]; $i++, $h_id++) {
			$excl = strlen($m[1]) + 1;
			$hash = preg_replace('/[^\da-z]/i', '_', $m[2]);
			
			for ($ret = ''; end($stack) >= $excl; $ret .= '</div>', array_pop($stack));
			
			$stack[] = $excl;
			
			$ret .= "<div class=\"par-div\" id=\"par-$h_id\"><h$excl id=\"$hash\">$m[2]";

			if ($is_enterprise) {
				if (!get_standalone_user($config['id_user'])) {
					if (wiki_get_write_acl ($config['id_user'], $page)) { 
						$ret .= "<span class=\"par-edit\">(<a href=\"$self" . "action=edit&amp;page=".u($page)."&amp;par=$h_id\">$T_EDIT</a>)</span>";
					}
				}
			} else {
				if (!get_standalone_user($config['id_user'])) {
					if (is_writable($PG_DIR . $page . '.txt')) {
						$ret .= "<span class=\"par-edit\">(<a href=\"$self" . "action=edit&amp;page=".u($page)."&amp;par=$h_id\">$T_EDIT</a>)</span>";
					}
				}
			}
	
			$CON = preg_replace('/' . preg_quote($m[0], '/') . '/', "$ret</h$excl>", $CON, 1);
			$TOC .= str_repeat("<ul>", $excl - 2).'<li><a href="'.$self.'page='.u($page).'#'.u($hash).'">'.$m[2].'</a></li>'.str_repeat("</ul>", $excl - 2);
		}

	
		$CON .= str_repeat('</div>', count($stack));
		
		$TOC = '<ul id="toc">' . preg_replace(array_fill(0, 5, "#</ul>\n*<ul>#"), array_fill(0, 5, ''), $TOC) . '</ul>';
		$TOC = str_replace(array('</li><ul>', '</ul><li>', '</ul></ul>', '<ul><ul>'), array('<ul>', '</ul></li><li>', '</ul></li></ul>', '<ul><li><ul>'), $TOC);
		
		$CON = preg_replace("/'--(.*)--'/Um", '<del>$1</del>', $CON); // strikethrough
		$CON = preg_replace("/'__(.*)__'/Um", '<u>$1</u>', $CON); // underlining
		$CON = preg_replace("/'''(.*)'''/Um", '<strong>$1</strong>', $CON); // bold
		$CON = preg_replace("/''(.*)''/Um", '<em>$1</em>', $CON); // italic
		$CON = str_replace('{br}', '<br style="clear:both"/>', $CON); // new line
		$CON = preg_replace('/-----*/', '<hr/>', $CON); // horizontal line
		$CON = str_replace('--', '&mdash;', $CON); // --
		
		$CON = preg_replace(array_fill(0, count($codes[1]) + 1, '/{CODE}/'), $codes[1], $CON, 1); // put HTML and "normal" codes back
		$CON = preg_replace(array_fill(0, count($htmlcodes[1]) + 1, '/{HTML}/'), $htmlcodes[1], $CON, 1);
		
		plugin('formatEnd');
	}
	
	plugin('formatFinished');
	
	// Loading template. If does not exist, use built-in default
	$html = file_exists($TEMPLATE) ?
		file_get_contents(clear_path($TEMPLATE)) : $fallback_template;
	
	// including pages in pure HTML
	while (preg_match('/{include:([^}]+)}/U', $html, $m)) {
		$inc = str_replace(array('{html}', '{/html}'), '', @file_get_contents("$PG_DIR$m[1].txt"));
		$html = str_replace($m[0], $inc, $html);
	}
	
	plugin('template'); // plugin templating
	
	
	$html = preg_replace('/\{([^}]* )?plugin:.+( [^}]*)?\}/U', '', $html); // get rid of absent plugin tags
	
	$has_perm = true;
	if ($is_enterprise) {
		$has_perm = wiki_get_write_acl($config['id_user'], $page); //if user has write permissions, he can read
		if (!$has_perm) {
			$has_perm = wiki_get_read_acl($config['id_user'], $page);
		}
	}
	
	if (!$has_perm) {
		$CON = __("You can't access this page");
	}
	
	$tpl_subs = array(
		'HEAD' => $HEAD . ($action ? '<meta name="robots" content="noindex, nofollow"/>' : ''),
		'SEARCH_FORM' => '<form action="'.$self_form.'" method="post"><span><input type="hidden" name="action" value="search"/><input type="submit" style="display:none;"/>',
		'\/SEARCH_FORM' => "</span></form>",
		'SEARCH_INPUT' => '<input type="text" name="query" value="'.h($query).'"/>',
		'SEARCH_SUBMIT' => "<input class=\"submit\" type=\"submit\" value=\"$T_SEARCH\"/>",
		'HOME' => "<a href=\"$self" . "page=".u($START_PAGE)."\">$T_HOME</a>",
		'RECENT_CHANGES' => "<a href=\"$self" . "action=recent\">$T_RECENT_CHANGES</a>",
		'READ' => "<a href=\"$self" . "page=".u($page). "&amp;action=read_acl\">Read ACL</a>",
		'WRITE' => "<a href=\"$self" . "page=".u($page). "&amp;action=write_acl\">Write ACL</a>",
		'ERROR' => $error,
		'HISTORY' => $page ? "<a href=\"$self" . "page=".u($page)."&amp;action=history\">$T_HISTORY</a>" : "",
		'PAGE_TITLE' => h($page == $START_PAGE && $page == $TITLE ? $WIKI_TITLE : $TITLE),
		'PAGE_TITLE_HEAD' => h($TITLE),
		'PAGE_URL' => u($page),
		'EDIT' => !$action?
			("<a href=\"$self" . "page=".u($page)."&amp;action=edit" . 
				(is_writable("$PG_DIR$page.txt") ? "\">$T_EDIT</a>" : "&amp;showsource=1\">$T_SHOW_SOURCE</a>"))
			: "",
		'WIKI_TITLE' => h($WIKI_TITLE),
		'LAST_CHANGED_TEXT' => $last_changed_ts ? $T_LAST_CHANGED : "",
		'LAST_CHANGED' => $last_changed_ts ? date($DATE_FORMAT, $last_changed_ts + $LOCAL_HOUR * 3600) : "",
		'CONTENT' => $action != "edit" ? $CON : "",
		'TOC' => $TOC,
		'SYNTAX' => $action == "edit" || $preview ? "<a href=\"$SYNTAX_PAGE\">$T_SYNTAX</a>" : "",
		'SHOW_PAGE' => $action == "edit" || $preview ? "<a href=\"$self" . "page=".u($page)."\">$T_SHOW_PAGE</a>" : "",
		'COOKIE' => '<a href="'.$self.'page='.u($page).'&amp;action='.u($action).'&amp;erasecookie=1">'.$T_ERASE_COOKIE.'</a>',
		'CONTENT_FORM' => $CON_FORM_BEGIN,
		'\/CONTENT_FORM' => $CON_FORM_END,
		'CONTENT_TEXTAREA' => $CON_TEXTAREA,
		'CONTENT_SUBMIT' => $CON_SUBMIT,
		'CONTENT_PREVIEW' => $CON_PREVIEW,
		'RENAME_TEXT' => $RENAME_TEXT,
		'RENAME_INPUT' => $RENAME_INPUT,
		'EDIT_SUMMARY_TEXT' => $EDIT_SUMMARY_TEXT,
		'EDIT_SUMMARY_INPUT' => $EDIT_SUMMARY,
		'FORM_PASSWORD' => $FORM_PASSWORD,
		'FORM_PASSWORD_INPUT' => $FORM_PASSWORD_INPUT
	);
	
	if ($action == '') {
		$tpl_subs['SYNTAX'] = "<a href=\"$SYNTAX_PAGE\">$T_SYNTAX</a>";
	}
	
	
	foreach ($tpl_subs as $tpl => $rpl) // substituting values

		$html = template_replace($tpl, $rpl, $html);
	
	header_lionwiki('Content-type: text/html; charset=UTF-8');
	
	echo($html);

}
Esempio n. 25
0
 public function toHtml($_version = 'dashboard', $options = '', $_cmdColor = null, $_cache = 2)
 {
     $version = jeedom::versionAlias($_version);
     $html = '';
     $template_name = 'cmd.' . $this->getType() . '.' . $this->getSubType() . '.' . $this->getTemplate($version, 'default');
     $template = '';
     if (!isset(self::$_templateArray[$version . '::' . $template_name])) {
         if ($this->getTemplate($version, 'default') != 'default') {
             if (config::byKey('active', 'widget') == 1) {
                 $template = getTemplate('core', $version, $template_name, 'widget');
             }
             if ($template == '') {
                 foreach (plugin::listPlugin(true) as $plugin) {
                     $template = getTemplate('core', $version, $template_name, $plugin->getId());
                     if ($template != '') {
                         break;
                     }
                 }
             }
             if ($template == '') {
                 $template_name = 'cmd.' . $this->getType() . '.' . $this->getSubType() . '.default';
                 $template = getTemplate('core', $version, $template_name);
             }
         } else {
             $template = getTemplate('core', $version, $template_name);
         }
         self::$_templateArray[$version . '::' . $template_name] = $template;
     } else {
         $template = self::$_templateArray[$version . '::' . $template_name];
     }
     $replace = array('#id#' => $this->getId(), '#name#' => $this->getDisplay('icon') != '' ? $this->getDisplay('icon') : $this->getName(), '#name_display#' => $this->getDisplay('icon') != '' ? $this->getDisplay('icon') : $this->getName(), '#history#' => '', '#displayHistory#' => 'display : none;', '#unite#' => $this->getUnite(), '#minValue#' => $this->getConfiguration('minValue', 0), '#maxValue#' => $this->getConfiguration('maxValue', 100), '#logicalId#' => $this->getLogicalId());
     if ($_cmdColor == null && $version != 'scenario') {
         $eqLogic = $this->getEqLogic();
         $vcolor = $version == 'mobile' ? 'mcmdColor' : 'cmdColor';
         if ($eqLogic->getPrimaryCategory() == '') {
             $replace['#cmdColor#'] = jeedom::getConfiguration('eqLogic:category:default:' . $vcolor);
         } else {
             $replace['#cmdColor#'] = jeedom::getConfiguration('eqLogic:category:' . $eqLogic->getPrimaryCategory() . ':' . $vcolor);
         }
     } else {
         $replace['#cmdColor#'] = $_cmdColor;
     }
     if ($this->getDisplay('doNotShowNameOnView') == 1 && ($_version == 'dview' || $_version == 'mview')) {
         $replace['#name_display#'] = '';
         $replace['#name#'] = '';
     } else {
         if ($this->getDisplay('doNotShowNameOnDashboard') == 1 && ($_version == 'mobile' || $_version == 'dashboard')) {
             $replace['#name_display#'] = '';
             $replace['#name#'] = '';
         } else {
             $replace['#name_display#'] .= '<br/>';
         }
     }
     if ($this->getType() == 'info') {
         $replace['#state#'] = '';
         $replace['#tendance#'] = '';
         $replace['#state#'] = $this->execCmd(null, $_cache);
         if (strpos($replace['#state#'], 'error::') !== false) {
             $template = getTemplate('core', $version, 'cmd.error');
             $replace['#state#'] = str_replace('error::', '', $replace['#state#']);
         } else {
             if ($this->getSubType() == 'binary' && $this->getDisplay('invertBinary') == 1) {
                 $replace['#state#'] = $replace['#state#'] == 1 ? 0 : 1;
             }
         }
         if (method_exists($this, 'formatValueWidget')) {
             $replace['#state#'] = $this->formatValueWidget($replace['#state#']);
         }
         $replace['#collectDate#'] = $this->getCollectDate();
         $replace['#valueDate#'] = $this->getValueDate();
         if ($this->getIsHistorized() == 1) {
             $replace['#history#'] = 'history cursor';
             if (config::byKey('displayStatsWidget') == 1 && strpos($template, '#displayHistory#') !== false) {
                 $showStat = true;
                 if ($this->getDisplay('doNotShowStatOnDashboard') == 1 && $_version == 'dashboard') {
                     $showStat = false;
                 }
                 if ($this->getDisplay('doNotShowStatOnView') == 1 && ($_version == 'dview' || $_version == 'mview')) {
                     $showStat = false;
                 }
                 if ($this->getDisplay('doNotShowStatOnMobile') == 1 && $_version == 'mobile') {
                     $showStat = false;
                 }
                 if ($showStat) {
                     $startHist = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' -' . config::byKey('historyCalculPeriod') . ' hour'));
                     $replace['#displayHistory#'] = '';
                     $historyStatistique = $this->getStatistique($startHist, date('Y-m-d H:i:s'));
                     if ($historyStatistique['avg'] == 0 && $historyStatistique['min'] == 0 && $historyStatistique['max'] == 0) {
                         $replace['#averageHistoryValue#'] = round($replace['#state#'], 1);
                         $replace['#minHistoryValue#'] = round($replace['#state#'], 1);
                         $replace['#maxHistoryValue#'] = round($replace['#state#'], 1);
                     } else {
                         $replace['#averageHistoryValue#'] = round($historyStatistique['avg'], 1);
                         $replace['#minHistoryValue#'] = round($historyStatistique['min'], 1);
                         $replace['#maxHistoryValue#'] = round($historyStatistique['max'], 1);
                     }
                     $startHist = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' -' . config::byKey('historyCalculTendance') . ' hour'));
                     $tendance = $this->getTendance($startHist, date('Y-m-d H:i:s'));
                     if ($tendance > config::byKey('historyCalculTendanceThresholddMax')) {
                         $replace['#tendance#'] = 'fa fa-arrow-up';
                     } else {
                         if ($tendance < config::byKey('historyCalculTendanceThresholddMin')) {
                             $replace['#tendance#'] = 'fa fa-arrow-down';
                         } else {
                             $replace['#tendance#'] = 'fa fa-minus';
                         }
                     }
                 }
             }
         }
         $parameters = $this->getDisplay('parameters');
         if (is_array($parameters)) {
             foreach ($parameters as $key => $value) {
                 $replace['#' . $key . '#'] = $value;
             }
         }
         return template_replace($replace, $template);
     } else {
         $cmdValue = $this->getCmdValue();
         if (is_object($cmdValue) && $cmdValue->getType() == 'info') {
             $replace['#state#'] = $cmdValue->execCmd(null, 2);
             $replace['#valueName#'] = $cmdValue->getName();
             $replace['#unite#'] = $cmdValue->getUnite();
         } else {
             $replace['#state#'] = $this->getLastValue() != null ? $this->getLastValue() : '';
             $replace['#valueName#'] = $this->getName();
             $replace['#unite#'] = $this->getUnite();
         }
         $parameters = $this->getDisplay('parameters');
         if (is_array($parameters)) {
             foreach ($parameters as $key => $value) {
                 $replace['#' . $key . '#'] = $value;
             }
         }
         $replace['#valueName#'] .= '<br/>';
         $html .= template_replace($replace, $template);
         if (trim($html) == '') {
             return $html;
         }
         if ($options != '') {
             $options = jeedom::toHumanReadable($options);
             if (is_json($options)) {
                 $options = json_decode($options, true);
             }
             if (is_array($options)) {
                 foreach ($options as $key => $value) {
                     $replace['#' . $key . '#'] = $value;
                 }
             }
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'message') {
             if (!isset($replace['#title#'])) {
                 $replace['#title#'] = '';
             }
             if (!isset($replace['#message#'])) {
                 $replace['#message#'] = '';
             }
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'slider' && !isset($replace['#slider#'])) {
             $replace['#slider#'] = '';
         }
         if ($version == 'scenario' && $this->getType() == 'action' && $this->getSubtype() == 'slider' && !isset($replace['#color#'])) {
             $replace['#color#'] = '';
         }
         $replace['#title_placeholder#'] = $this->getDisplay('title_placeholder', __('Titre', __FILE__));
         $replace['#message_placeholder#'] = $this->getDisplay('message_placeholder', __('Message', __FILE__));
         $replace['#message_disable#'] = $this->getDisplay('message_disable', 0);
         $replace['#title_disable#'] = $this->getDisplay('title_disable', 0);
         $replace['#title_possibility_list#'] = $this->getDisplay('title_possibility_list', '');
         $replace['#slider_placeholder#'] = $this->getDisplay('slider_placeholder', __('Valeur', __FILE__));
         $html = template_replace($replace, $html);
         return $html;
     }
 }
Esempio n. 26
0
 public function getData($_startDate = null, $_endDate = null)
 {
     $nowtime = floatval(strtotime(date('Y-m-d H:i:s') . " UTC"));
     $now = strtotime(date('Y-m-d H:i:s'));
     $archiveTime = (config::byKey('historyArchiveTime') + 1) * 3600;
     $packetTime = config::byKey('historyArchivePackage') * 3600;
     $return = array('history' => array('power' => array(), 'consumption' => null), 'stats' => array('minPower' => null, 'maxPower' => null), 'real' => array('power' => 0, 'consumption' => 0));
     $cmd_histories = array();
     preg_match_all("/#([0-9]*)#/", $this->getPower(), $matches);
     foreach ($matches[1] as $cmd_id) {
         if (is_numeric($cmd_id)) {
             $cmd = cmd::byId($cmd_id);
             if (is_object($cmd) && $cmd->getIsHistorized() == 1) {
                 $prevDatetime = null;
                 $prevValue = 0;
                 foreach ($cmd->getHistory($_startDate, $_endDate) as $history) {
                     if (!isset($cmd_histories[$history->getDatetime()])) {
                         $cmd_histories[$history->getDatetime()] = array();
                     }
                     if (!isset($cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'])) {
                         if ($prevDatetime != null) {
                             $datetime = strtotime($history->getDatetime());
                             while ($now - strtotime($prevDatetime) > $archiveTime && strtotime($prevDatetime) < $datetime) {
                                 $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + $packetTime);
                                 $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = 0;
                             }
                             while ($now - strtotime($prevDatetime) > 300 && strtotime($prevDatetime) < $datetime) {
                                 $prevDatetime = date('Y-m-d H:i:00', strtotime($prevDatetime) + 300);
                                 $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = $prevValue;
                             }
                         }
                         if (strtotime($history->getDatetime()) <= $now) {
                             $cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'] = $history->getValue();
                         }
                     }
                     $prevDatetime = $history->getDatetime();
                     $prevValue = $history->getValue();
                 }
             }
         }
     }
     foreach ($cmd_histories as $datetime => $cmd_history) {
         $datetime = floatval(strtotime($datetime . " UTC"));
         $calcul = template_replace($cmd_history, $this->getPower());
         try {
             if ($datetime <= $nowtime) {
                 $test = new evaluate();
                 $result = floatval($test->Evaluer($calcul));
                 if ($this->getConsumption() == '' && count($return['history']['power']) > 0) {
                     $last_datetime = end(array_keys($return['history']['power']));
                     if ($datetime - $last_datetime > 0) {
                         $last_value = end($return['history']['power']);
                         $return['history']['consumption'][$datetime] = array($datetime, $last_value[1] * (($datetime - $last_datetime) / 1000) / 3600);
                         $return['real']['consumption'] += $return['history']['consumption'][$datetime][1];
                     }
                 }
                 $return['history']['power'][$datetime] = array($datetime * 1000, $result);
                 if ($return['stats']['minPower'] === null || $return['stats']['minPower'] > $result) {
                     $return['stats']['minPower'] = $result;
                 }
                 if ($return['stats']['maxPower'] === null || $return['stats']['maxPower'] < $result) {
                     $return['stats']['maxPower'] = $result;
                 }
             }
         } catch (Exception $e) {
         }
     }
     if ($this->getConsumption() == '' && count($return['history']['power']) > 0) {
         $last_datetime = end(array_keys($return['history']['power']));
         $last_value = end($return['history']['power']);
         if ($datetime - $last_datetime > 0) {
             $return['history']['consumption'][$datetime] = array($datetime * 1000, $last_value[1] * (($nowtime - $last_datetime) / 1000) / 3600);
             $return['real']['consumption'] += $return['history']['consumption'][$datetime][1];
         }
     }
     $calcul = cmd::cmdToValue($this->getPower());
     try {
         $test = new evaluate();
         $result = floatval($test->Evaluer($calcul));
         $return['real']['power'] = $result;
         $return['history']['power'][$nowtime] = array($nowtime * 1000, $result);
     } catch (Exception $e) {
     }
     if ($this->getConsumption() != '') {
         $cmd_histories = array();
         preg_match_all("/#([0-9]*)#/", $this->getConsumption(), $matches);
         foreach ($matches[1] as $cmd_id) {
             if (is_numeric($cmd_id)) {
                 $cmd = cmd::byId($cmd_id);
                 if (is_object($cmd) && $cmd->getIsHistorized() == 1) {
                     $prevDatetime = null;
                     foreach ($cmd->getHistory($_startDate, $_endDate) as $history) {
                         if (!isset($cmd_histories[$history->getDatetime()])) {
                             $cmd_histories[$history->getDatetime()] = array();
                         }
                         if (!isset($cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'])) {
                             if ($prevDatetime != null) {
                                 $datetime = strtotime($history->getDatetime());
                                 while ($now - strtotime($prevDatetime) > $archiveTime && strtotime($prevDatetime) < $datetime) {
                                     $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + $packetTime);
                                     $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = 0;
                                 }
                                 while ($now - strtotime($prevDatetime) < 300 && strtotime($prevDatetime) < $datetime) {
                                     $prevDatetime = date('Y-m-d H:00:00', strtotime($prevDatetime) + 300);
                                     $cmd_histories[$prevDatetime]['#' . $cmd_id . '#'] = $prevValue;
                                 }
                             }
                             if (strtotime($history->getDatetime()) <= $now) {
                                 $cmd_histories[$history->getDatetime()]['#' . $cmd_id . '#'] = $history->getValue();
                             }
                         }
                         $prevDatetime = $history->getDatetime();
                         $prevValue = $history->getValue();
                     }
                 }
             }
         }
         foreach ($cmd_histories as $datetime => $cmd_history) {
             $datetime = floatval(strtotime($datetime . " UTC"));
             $calcul = template_replace($cmd_history, $this->getConsumption());
             try {
                 if ($datetime <= $nowtime) {
                     $test = new evaluate();
                     $result = floatval($test->Evaluer($calcul));
                     $return['history']['consumption'][$datetime] = array($datetime * 1000, $result);
                 }
             } catch (Exception $e) {
             }
         }
         $calcul = cmd::cmdToValue($this->getConsumption());
         try {
             $test = new evaluate();
             $result = floatval($test->Evaluer($calcul));
             $return['real']['consumption'] = $result;
             $return['history']['consumption'][$nowtime] = array($nowtime * 1000, $result);
         } catch (Exception $e) {
         }
     }
     if (is_array($return['history']['consumption'])) {
         ksort($return['history']['consumption']);
     }
     if (is_array($return['history']['power'])) {
         ksort($return['history']['power']);
     }
     return $return;
 }
Esempio n. 27
0
 * Operator functions
 */
include "functions/functions.operator.php";
$operator_id = get_operator_id();
$js = array("js/popup.js", "include/jquery/jquery-1.4.2.min.js", "include/jquery-ui/jquery-ui.min.js");
if (AUTO_LOGOUT_MINUTES !== false) {
    $js[] = "js/childnap.js";
}
xhtml_head(T_("Respondent Selection") . " - " . T_("Project end"), true, array("include/bootstrap/css/bootstrap.min.css", "css/rs.css"), $js);
$case_id = get_case_id($operator_id);
$questionnaire_id = get_questionnaire_id($operator_id);
//display introduction text
$sql = "SELECT rs_project_end\r\n\tFROM questionnaire\r\n\tWHERE questionnaire_id = '{$questionnaire_id}'";
$r = $db->GetRow($sql);
if (!empty($r['rs_project_end'])) {
    print "<p class='rstext well'>" . template_replace($r['rs_project_end'], $operator_id, $case_id) . "</p>";
}
print "<p class='well'>";
if (!is_voip_enabled($operator_id) && AUTO_COMPLETE_OUTCOME) {
    end_call($operator_id, 10);
    print T_("Call automatically ended with outcome:") . "&ensp;<b>" . T_("Complete") . "</b>";
    //check for alternate interface
    if (ALTERNATE_INTERFACE && !is_voip_enabled($operator_id)) {
        print "&emsp;<a href=\"javascript:parent.location.href = 'index_interface2.php?endcase=endcase'\" class='btn btn-primary'>" . T_("End case") . "</a>";
    }
} else {
    print T_("End call with outcome:") . "&emsp;<a class='btn btn-primary' ";
    //check for alternate interface
    if (ALTERNATE_INTERFACE && !is_voip_enabled($operator_id)) {
        print "href=\"javascript:parent.location.href = 'index_interface2.php?outcome=10&amp;endcase=endcase'\">";
    } else {
Esempio n. 28
0
 public function toHtml($_version = 'dashboard', $_withValue = true)
 {
     if ($this->getIsEnable() != 1) {
         return '';
     }
     $weather = $this->getWeatherArea();
     if (!is_array($weather)) {
         return false;
     }
     $replace = array('#icone#' => self::getIconFromCondition($weather['condition']['text']), '#city#' => $weather['location']['city'], '#condition#' => $weather['condition']['text'], '#temperature#' => $weather['condition']['temperature'], '#windspeed#' => $weather['wind']['speed'], '#humidity#' => $weather['atmosphere']['humidity'], '#pressure#' => $weather['atmosphere']['pressure'], '#sunrise#' => $weather['astronomy']['sunrise'], '#sunset#' => $weather['astronomy']['sunset'], '#eqLink#' => $this->getLinkToConfiguration());
     $return = template_replace($replace, getTemplate('core', $_version, 'current', 'weather'));
     $i = 0;
     foreach ($weather['forecast'] as $forecast) {
         $replace = array('#day#' => $forecast['day'], '#condition#' => $forecast['condition'], '#low_temperature#' => $forecast['low_temperature'], '#hight_temperature#' => $forecast['high_temperature']);
         $return .= template_replace($replace, getTemplate('core', $_version, 'forecast', 'weather'));
     }
     return $return;
 }
 function template()
 {
     global $html, $action;
     if (!empty($action)) {
         return;
     }
     if (template_match("plugin:TAG_LIST", $html, $null)) {
         $html = template_replace("plugin:TAG_LIST", $this->tagList(), $html);
     }
     if (template_match("plugin:TAG_CLOUD", $html, $null)) {
         $html = template_replace("plugin:TAG_CLOUD", $this->tagCloud(), $html);
     }
 }
Esempio n. 30
0
 public function toHtml($_version)
 {
     if (!$this->hasRight('r')) {
         return '';
     }
     $sql = 'SELECT `value` FROM cache
 WHERE `key`="scenarioHtml' . $_version . $this->getId() . '"';
     $result = DB::Prepare($sql, array(), DB::FETCH_TYPE_ROW);
     if ($result['value'] != '') {
         return $result['value'];
     }
     $_version = jeedom::versionAlias($_version);
     $replace = array('#id#' => $this->getId(), '#state#' => $this->getState(), '#isActive#' => $this->getIsActive(), '#name#' => $this->getDisplay('name') != '' ? $this->getDisplay('name') : $this->getHumanName(), '#icon#' => $this->getIcon(), '#lastLaunch#' => $this->getLastLaunch(), '#scenarioLink#' => $this->getLinkToConfiguration());
     if (!isset(self::$_templateArray)) {
         self::$_templateArray = array();
     }
     if (!isset(self::$_templateArray[$_version])) {
         self::$_templateArray[$_version] = getTemplate('core', $_version, 'scenario');
     }
     $html = template_replace($replace, self::$_templateArray[$_version]);
     cache::set('scenarioHtml' . $_version . $this->getId(), $html, 0);
     return $html;
 }