/**
  * render form
  * 
  * TODO: if variable source doesn't matter, use REQUEST by removing POST from readVar()
  * @return string
  */
 public function render()
 {
     global $q_orig;
     // check if dada was sent
     if ($formData = readVar($this->getName(), false, $_POST)) {
         // reset all checkboxes
         foreach ($this->fields as $field) {
             if ($field->getFieldType() == "CHECKBOX") {
                 $field->setValue("off");
             }
         }
         // set values
         foreach ($formData as $key => $val) {
             $this->fields[$key]->setValue($val);
         }
         //validate values
         $isValid = true;
         foreach ($this->fields as $field) {
             if (!$field->isValid()) {
                 $isValid = false;
             }
         }
         if ($isValid) {
             if (!$this->validator || !is_callable($this->validator)) {
                 return "no or invalid validator given!";
             }
             $ret = call_user_func($this->validator, $this);
             // if ($ret!=true)
             // return $ret;
         }
     }
     // TODO: maybe use template?
     // render form
     $txt = "";
     if ($this->header) {
         $txt .= "<h1>{$this->header}</h1>";
     }
     if ($this->subheader) {
         $txt .= "<p>{$this->subheader}</p>";
     }
     $txt .= '<div class="form">' . NL;
     $txt .= '<form class="well form-vertical" id="verticalForm" action="?q=' . $q_orig . '" method="post">' . NL;
     if ($this->help_url) {
         $txt .= '<label class="ct_help_label"><a title="' . t("getting.help") . '" href="http://intern.churchtools.de?q=help&doc=' . $this->help_url . '" target="_clean">';
         $txt .= '<i class="icon-question-sign"></i></a></label>' . NL;
     }
     $requiredFields = false;
     // render fields
     foreach ($this->fields as $field) {
         $txt .= $field->render();
         if ($field->isRequired()) {
             $requiredFields = true;
         }
     }
     foreach ($this->buttons as $button) {
         $txt .= $button->render() . "&nbsp;";
     }
     $txt .= '</form>';
     if ($requiredFields) {
         $txt .= '<p class="note">' . t("fields.with.asterisk.has.to.be.filled") . '</p>' . NL;
     }
     $txt .= '</div>' . NL;
     return $txt;
 }
/**
 * echo ical for services to do from user id (read from request)
 */
function churchservice_ical()
{
    global $base_url, $config;
    if (!($id = readVar("id"))) {
        echo t("please.specify.id");
    }
    drupal_add_http_header('Content-Type', 'text/calendar;charset=utf-8', false);
    drupal_add_http_header('Content-Disposition', 'inline;filename="ChurchTools.ics"', false);
    drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', false);
    drupal_add_http_header('Cache-Control', 'private', false);
    $content = drupal_get_header();
    include_once './' . CHURCHSERVICE . '/churchservice_db.php';
    $arr = churchservice_getUserCurrentServices($id);
    // TODO: use txt Template
    $txt = "";
    foreach ($arr as $res) {
        $txt .= "BEGIN:VEVENT\r\n";
        $txt .= "ORGANIZER:MAILTO:" . readConf('site_mail', '') . "\r\n";
        if ($res->zugesagt_yn == 1) {
            $txt .= "SUMMARY:" . $res->dienst . " (" . $res->servicegroup . ")\r\n";
        } else {
            $txt .= "SUMMARY:Anfrage: " . $res->dienst . " (" . $res->servicegroup . ")?\r\n";
        }
        $txt .= "X-MICROSOFT-CDO-BUSYSTATUS:BUSY\r\n";
        $txt .= "URL:" . $base_url . "/?q=churchservice/entrylist\r\n";
        if ($res->ort != "") {
            $txt .= "LOCATION:" . $res->ort . "\r\n";
        }
        $txt .= "DESCRIPTION:" . $res->dienst . " (" . $res->servicegroup . ") bei " . $res->event . ".";
        if ($res->zugesagt_yn == 1) {
            $txt .= "\r\n";
        } else {
            $txt .= " " . t("request.from") . " {$res->vorname} {$res->name} [{$res->modified_pid}]\r\n";
        }
        $txt .= "DTSTAMP:" . $res->modified_date . "\r\n";
        $txt .= "UID:" . $res->eventservice_id . "\r\n";
        $txt .= "DTSTART;TZID=" . $config["timezone"] . ":" . $res->datum_start . "\r\n";
        $txt .= "DTEND;TZID=" . $config["timezone"] . ":" . $res->datum_end . "\r\n";
        $txt .= "END:VEVENT\r\n";
    }
    echo surroundWithVCALENDER($txt);
}
/**
 * Main entry point for churchtools.
 * This will be called from /index.php
 * Function loads i18n, configuration, check data security.
 * If everything is ok, it calls churchtools_processRequest()
 */
function churchtools_app()
{
    global $q, $q_orig, $currentModule, $add_header, $config, $mapping, $content, $base_url, $files_dir, $user, $embedded, $i18n;
    include_once CHURCHCORE . "/churchcore_db.php";
    $files_dir = DEFAULT_SITE;
    // which module is requested?
    $q = $q_orig = readVar("q", userLoggedIn() ? "home" : readConf("site_startpage", "home"));
    // $currentModule is needed for class autoloading and maybe other include paths
    list($currentModule) = explode('/', readVar("q"));
    // get first part of $q or churchcore
    $embedded = readVar("embedded", false);
    $base_url = getBaseUrl();
    $config = loadConfig();
    if ($config) {
        if (db_connect()) {
            // DBConfig overwrites the config files
            loadDBConfig();
            date_default_timezone_set(variable_get("timezone", "Europe/Berlin"));
            if (isset($_COOKIE["language"])) {
                $config["language"] = $_COOKIE["language"];
            }
            // Load i18n churchcore-bundle
            if (!isset($config["language"])) {
                if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
                    $config["language"] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
                } else {
                    $config["language"] = "de";
                }
            }
            $i18n = new TextBundle(CHURCHCORE . "/resources/messages");
            $i18n->load("churchcore", $config["language"] != null ? $config["language"] : null);
            // Session Init
            if (!file_exists($files_dir . "/tmp")) {
                @mkdir($files_dir . "/tmp", 0775, true);
            }
            if (!file_exists($files_dir . "/tmp")) {
                // Admin should act accordingly, default suggestion is 0755.
                addErrorMessage(t("permission.denied.write.dir", $files_dir));
            } else {
                session_save_path($files_dir . "/tmp");
            }
            session_name("ChurchTools_" . $config["db_name"]);
            session_start();
            register_shutdown_function('handleShutdown');
            // Check for offline mode. If it's activated display message and return false;
            if (readConf("site_offline") == 1) {
                if (!isset($_SESSION["user"]) || !in_array($_SESSION["user"]->id, readconf("admin_ids"))) {
                    echo t("site.is.down");
                    return false;
                }
            }
            $embedded = readVar("embedded", false);
            $mapping = loadMapping();
            $success = true;
            // Check for DB-Updates and loginstr only if this is not an ajax call.
            if (strrpos($q, "ajax") === false) {
                $success = checkForDBUpdates();
            }
            if ($success) {
                // Is there a loginstr which does not fit to the current logged in user?
                if (readVar("loginstr") && readVar("id") && userLoggedIn() && $_SESSION["user"]->id != readVar("id")) {
                    logout_current_user();
                    session_start();
                } else {
                    loadUserObjectInSession();
                }
            }
            if ($success) {
                if (isset($_SESSION['user'])) {
                    $user = $_SESSION['user'];
                }
                // Accept data security?
                if (userLoggedIn() && !isset($_SESSION["simulate"]) && $q != "logout" && isset($config["accept_datasecurity"]) && $config["accept_datasecurity"] == 1 && !isset($user->acceptedsecurity)) {
                    $content .= pleaseAcceptDatasecurity();
                } else {
                    $content .= churchtools_processRequest($q);
                }
            }
        }
    }
    include INCLUDES . "/header.php";
    echo $content;
    include INCLUDES . "/body.php";
}
 /**
  * process uploaded files (test, save to DB + upload dir)
  *
  * @param string $uploadDirectory         
  * @param bool $replaceOldFile       
  *
  * @return array ('success'=>true) or ('error'=>'error message')
  */
 function handleUpload($uploadDirectory, $replaceOldFile = false)
 {
     global $user;
     if (!is_writable($uploadDirectory)) {
         return array('error' => t("uploaddircetdory.not.writable"));
     }
     if (!$this->file) {
         return array('error' => t('no.uploaded.files'));
     }
     $size = $this->file->getSize();
     if ($size == 0) {
         return array('error' => t('file.is.empty'));
     }
     if ($size > $this->sizeLimit) {
         return array('error' => t('file.is.to.large'));
     }
     $pathinfo = pathinfo($this->file->getName());
     $bezeichnung = $pathinfo['filename'];
     // $filename = "aaaaa";
     $filename = md5(uniqid());
     $ext = $pathinfo['extension'];
     if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
         return array('error' => t('invalid.fileextension.should.be.one.of.this', implode(', ', $this->allowedExtensions)));
     }
     if ($domainType = readConf("domain_type") && ($domainId = readConf("domain_id"))) {
         $dt = new DateTime();
         $id = db_insert('cc_file')->fields(array("domain_type" => $domainType, "domain_id" => $domainId, "filename" => $filename . '.' . $ext, "bezeichnung" => $bezeichnung . '.' . $ext, "modified_date" => $dt->format('Y-m-d H:i:s'), "modified_pid" => $user->id))->execute();
     } else {
         $id = null;
     }
     $filename_absolute = "{$uploadDirectory}{$filename}.{$ext}";
     if ($this->file->save($filename_absolute)) {
         // If image should be resized
         if ($resize = readVar("resize") && $this->check_jpeg($filename_absolute)) {
             list($width, $height) = getimagesize($filename_absolute);
             if ($width > $height) {
                 $new_width = $resize;
                 $new_height = $height * $new_width / $width;
             } else {
                 $new_height = $resize;
                 $new_width = $width * $new_height / $height;
             }
             $image_p = imagecreatetruecolor($new_width, $new_height);
             $image = imagecreatefromjpeg($filename_absolute);
             imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
             // Output
             imagejpeg($image_p, $filename_absolute, 100);
         }
         return array('success' => true, "id" => $id, "filename" => "{$filename}.{$ext}", "bezeichnung" => "{$bezeichnung}.{$ext}");
     } else {
         return array('error' => t('could.not.save.file.upvoad.canceled.ot.server.error'));
     }
 }
function churchservice_getUserOpenServices()
{
    global $user;
    if ($id = readVar("eventservice_id")) {
        include_once './' . CHURCHSERVICE . '/churchservice_ajax.php';
        $reason = readVar("reason", null);
        if (readVar("zugesagt_yn") == 1) {
            churchservice_updateEventService($id, $user->vorname . " " . $user->name, $user->id, 1, $reason);
        } else {
            churchservice_updateEventService($id, null, null, 0, $reason);
        }
        addInfoMessage("Danke für deine Rückmeldung!");
    }
    include_once './' . CHURCHDB . '/churchdb_db.php';
    $txt = "";
    $pid = $user->id;
    $txt1 = "";
    $res = db_query("SELECT cal.bezeichnung event, e.id event_id, es.id eventservice_id, allowtonotebyconfirmation_yn,\n                       DATE_FORMAT(e.startdate, '%d.%m.%Y %H:%i') datum, s.bezeichnung service, \n                       s.id service_id, sg.bezeichnung servicegroup, concat(p.vorname, ' ', p.name) as modifieduser, p.id modified_pid\n                   FROM {cs_eventservice} es, {cs_event} e, {cs_servicegroup} sg, {cs_service} s, {cdb_person} p, {cc_cal} cal \n                    where e.valid_yn=1 and cal.id=e.cc_cal_id and cdb_person_id={$user->id} and e.startdate>=current_date() and es.modified_pid=p.id and \n                    zugesagt_yn=0 and es.valid_yn=1 and es.event_id=e.id and es.service_id=s.id \n                    and sg.id=s.servicegroup_id order by datum ");
    $nr = 0;
    $txt2 = "";
    foreach ($res as $arr) {
        $nr = $nr + 1;
        $txt2 = $txt2 . '<div class="service-request" style="display:none;" ' . 'data-id="' . $arr->eventservice_id . '" data-modified-user="******" ';
        if ($arr->allowtonotebyconfirmation_yn == 1) {
            $txt2 .= 'data-comment-confirm="' . $arr->allowtonotebyconfirmation_yn . '" ';
        }
        if (user_access("view", "churchdb")) {
            $txt2 .= 'data-modified-pid="' . $arr->modified_pid . '" ';
        }
        $txt2 .= ">";
        $txt2 .= '<a href="?q=churchservice&id=' . $arr->event_id . '">';
        $txt2 .= $arr->datum . " - " . $arr->event . "</a>: ";
        $txt2 .= '<a href="?q=churchservice&id=' . $arr->event_id . '"><b>' . $arr->service . "</b></a> (" . $arr->servicegroup . ")";
        $files = churchcore_getFilesAsDomainIdArr("service", $arr->event_id);
        $txt .= '<span class="pull-right">';
        if (isset($files) && isset($files[$arr->event_id])) {
            $i = 0;
            foreach ($files[$arr->event_id] as $file) {
                $i++;
                if ($i <= 3) {
                    $txt .= churchcore_renderFile($file) . "&nbsp;";
                } else {
                    $txt .= "...";
                }
            }
        }
        $txt .= "</span>";
        $txt2 .= '<div style="margin-left:16px;margin-bottom:10px;" class="service-request-answer"></div>';
        $txt2 .= '</div>';
    }
    if ($txt2 != "") {
        $txt = $txt . $txt1 . $txt2 . '<p align="right"><a href="#" style="display:none" class="service-request-show-all">' . t("show.all") . '</a>';
    }
    return $txt;
}