Exemple #1
0
 /**
  * Stores the user domain settings of a user.
  */
 public function store_action()
 {
     $this->check_ticket();
     $any_change = false;
     $userdomain_delete = Request::optionArray('userdomain_delete');
     if (count($userdomain_delete) > 0) {
         foreach ($userdomain_delete as $id) {
             $domain = new UserDomain($id);
             $domain->removeUser($this->user->user_id);
         }
         $any_change = true;
     }
     $new_userdomain = Request::option('new_userdomain');
     if ($new_userdomain && $new_userdomain != 'none') {
         $domain = new UserDomain($new_userdomain);
         $domain->addUser($this->user->user_id);
         $any_change = true;
     }
     if ($any_change) {
         $this->reportSuccess(_('Die Zuordnung zu Nutzerdomänen wurde geändert.'));
         setTempLanguage($this->user->user_id);
         $this->postPrivateMessage(_("Die Zuordnung zu Nutzerdomänen wurde geändert!\n"));
         restoreLanguage();
     }
     $this->redirect('settings/userdomains');
 }
Exemple #2
0
 /**
  * Overwrites the parent method. This method combines messages with the same
  * content and prepares them for sending them as a mail with multiple 
  * recepients instead of one mail for each recipient.
  * The actual sending task is done bulkSend().
  * 
  * @global object $user
  * 
  * @param string $rec_user_id  user_id of recipient
  * @param string $snd_user_id  user_id of sender
  * @param string $message      the message
  * @param string $subject      subject for the message
  * @param string $message_id   the message_id in the database
  */
 function sendingEmail($rec_user_id, $snd_user_id, $message, $subject, $message_id)
 {
     global $user;
     $db4 = new DB_Seminar("SELECT user_id, Email FROM auth_user_md5 WHERE user_id = '{$rec_user_id}';");
     $db4->next_record();
     if ($to = $db4->f("Email")) {
         $rec_fullname = 'Sie';
         setTempLanguage($db4->f("user_id"));
         if (empty($this->bulk_mail[md5($message)][getenv('LANG')])) {
             $title = "[Stud.IP - " . $GLOBALS['UNI_NAME_CLEAN'] . "] " . stripslashes(kill_format(str_replace(array("\r", "\n"), '', $subject)));
             if ($snd_user_id != "____%system%____") {
                 $snd_fullname = get_fullname($snd_user_id);
                 $db4->query("SELECT Email FROM auth_user_md5 WHERE user_id = '{$user->id}'");
                 $db4->next_record();
                 $reply_to = $db4->f("Email");
             }
             $template = $GLOBALS['template_factory']->open('mail/text');
             $template->set_attribute('message', kill_format(stripslashes($message)));
             $template->set_attribute('rec_fullname', $rec_fullname);
             $mailmessage = $template->render();
             $template = $GLOBALS['template_factory']->open('mail/html');
             $template->set_attribute('lang', getUserLanguagePath($rec_user_id));
             $template->set_attribute('message', stripslashes($message));
             $template->set_attribute('rec_fullname', $rec_fullname);
             $mailhtml = $template->render();
             $this->bulk_mail[md5($message)][getenv('LANG')] = array('text' => $mailmessage, 'html' => $mailhtml, 'title' => $title, 'reply_to' => $reply_to, 'message_id' => $message_id, 'users' => array());
         }
         $this->bulk_mail[md5($message)][getenv('LANG')]['users'][$db4->f('user_id')] = $to;
         restoreLanguage();
     }
 }
Exemple #3
0
 /**
  * Set the posting denoted by the passed topic_id as liked for the
  * currently logged in user
  * 
  * @param string $topic_id
  */
 static function like($topic_id)
 {
     $stmt = DBManager::get()->prepare("REPLACE INTO\n            forum_likes (topic_id, user_id)\n            VALUES (?, ?)");
     $stmt->execute(array($topic_id, $GLOBALS['user']->id));
     // get posting owner
     $data = ForumEntry::getConstraints($topic_id);
     // notify owner of posting about the like
     setTempLanguage($data['user_id']);
     $notification = get_fullname($GLOBALS['user']->id) . _(' gefällt einer deiner Forenbeiträge!');
     restoreLanguage();
     PersonalNotifications::add($data['user_id'], PluginEngine::getURL('coreforum/index/index/' . $topic_id . '?highlight_topic=' . $topic_id . '#' . $topic_id), $notification, $topic_id, Icon::create('forum', 'clickable')->asImagePath(40));
 }
Exemple #4
0
 /**
  * Notifies the user with Stud.IP-message that/he/she was mentioned in a
  * blubber-posting.
  * @param type $posting
  */
 public function mention($posting)
 {
     $messaging = new messaging();
     setTempLanguage($this->getId());
     $url = $GLOBALS['ABSOLUTE_URI_STUDIP'] . "plugins.php/blubber/streams/thread/" . $posting['root_id'] . ($posting['context_type'] === "course" ? '?cid=' . $posting['Seminar_id'] : "");
     $body = sprintf(gettext("%s hat Sie in einem Blubber erwähnt. Zum Beantworten klicken auf Sie auf folgenen Link:\n\n%s\n"), get_fullname(), $url);
     if ($posting['context_type'] === "course" && !$GLOBALS['perm']->have_studip_perm("user", $posting['Seminar_id'], $this->getId())) {
         $body .= "\n\n" . _("Sie sind noch kein Mitglied der zugehörigen Veranstaltung. Melden Sie sich erst hier an, damit Sie den Blubber sehen können: ") . ($GLOBALS['SEM_CLASS'][$GLOBALS['SEM_TYPE'][Course::find($posting['Seminar_id'])->status]['class']]['studygroup_mode'] ? $GLOBALS['ABSOLUTE_URI_STUDIP'] . "dispatch.php/course/studygroup/details/" . $posting['Seminar_id'] : $GLOBALS['ABSOLUTE_URI_STUDIP'] . "dispatch.php/course/details?sem_id=" . $posting['Seminar_id']);
     }
     $mention_text = _("Sie wurden erwähnt.");
     restoreLanguage();
     $messaging->insert_message($body, $this['username'], $GLOBALS['user']->id, null, null, null, null, $mention_text);
 }
Exemple #5
0
 function setupAuth($router)
 {
     // Detect consumer
     $consumer = Consumer\Base::detectConsumer();
     if (!$consumer) {
         throw new RouterException(401, 'Unauthorized (no consumer)');
     }
     // Set authentication if present
     if ($user = $consumer->getUser()) {
         // Skip fake authentication if user is already logged in
         if ($GLOBALS['user']->id !== $user->id) {
             $GLOBALS['auth'] = new Seminar_Auth();
             $GLOBALS['auth']->auth = array('uid' => $user->user_id, 'uname' => $user->username, 'perm' => $user->perms);
             $GLOBALS['user'] = new Seminar_User($user->user_id);
             $GLOBALS['perm'] = new Seminar_Perm();
             $GLOBALS['MAIL_VALIDATE_BOX'] = false;
         }
         setTempLanguage($GLOBALS['user']->id);
     }
     return $consumer->getUser();
 }
Exemple #6
0
 /**
  * Upload a new avatar or removes the current avatar.
  * Upon Sends an information email to the user if the action was not invoked
  * by himself.
  */
 public function upload_action()
 {
     $this->check_ticket();
     if (Request::submitted('reset')) {
         Avatar::getAvatar($this->user->user_id)->reset();
         Visibility::removePrivacySetting('picture', $this->user->user_id);
         $this->reportSuccess(_('Bild gelöscht.'));
     } elseif (Request::submitted('upload')) {
         try {
             Avatar::getAvatar($this->user->user_id)->createFromUpload('imgfile');
             NotificationCenter::postNotification('AvatarDidUpload', $this->user->user_id);
             $message = _('Die Bilddatei wurde erfolgreich hochgeladen. ' . 'Eventuell sehen Sie das neue Bild erst, nachdem Sie diese Seite ' . 'neu geladen haben (in den meisten Browsern F5 drücken).');
             $this->reportSuccess($message);
             setTempLanguage($this->user->user_id);
             $this->postPrivateMessage(_("Ein neues Bild wurde hochgeladen.\n"));
             restoreLanguage();
             Visibility::addPrivacySetting(_('Eigenes Bild'), 'picture', 'commondata', 1, $this->user->user_id);
         } catch (Exception $e) {
             $this->reportError($e->getMessage());
         }
     }
     $this->redirect('settings/avatar');
 }
Exemple #7
0
 /**
  * Stores the study information of a user (institute-wise).
  */
 public function store_in_action()
 {
     $this->check_ticket();
     $inst_delete = Request::optionArray('inst_delete');
     if (count($inst_delete) > 0) {
         $query = "DELETE FROM user_inst WHERE user_id = ? AND Institut_id = ?";
         $statement = DBManager::get()->prepare($query);
         foreach ($inst_delete as $institute_id) {
             $statement->execute(array($this->user->user_id, $institute_id));
             if ($statement->rowCount() > 0) {
                 log_event('INST_USER_DEL', $institute_id, $this->user->user_id);
                 $delete = true;
             }
         }
     }
     $new_inst = Request::option('new_inst');
     if ($new_inst) {
         $query = "INSERT IGNORE INTO user_inst\n                        (user_id, Institut_id, inst_perms)\n                      VALUES (?, ?, 'user')";
         $statement = DBManager::get()->prepare($query);
         $statement->execute(array($this->user->user_id, $new_inst));
         if ($statement->rowCount() > 0) {
             log_event('INST_USER_ADD', $new_inst, $this->user->user_id, 'user');
             $new = true;
         }
     }
     if ($delete || $new) {
         $this->reportSuccess(_('Die Zuordnung zu Einrichtungen wurde geändert.'));
         setTempLanguage($this->user->user_id);
         $this->postPrivateMessage(_("Die Zuordnung zu Einrichtungen wurde geändert!\n"));
         restoreLanguage();
     }
     $this->redirect('settings/studies');
 }
Exemple #8
0
 /**
  * check, if the default root-node for this seminar exists and make sure
  * the default category exists as well
  *
  * @param type $seminar_id
  *
  * @return void
  */
 function checkRootEntry($seminar_id)
 {
     setTempLanguage($GLOBALS['DEFAULT_LANGUAGE']);
     // check, if the root entry in the topic tree exists
     $stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries\n            WHERE topic_id = ? AND seminar_id = ?");
     $stmt->execute(array($seminar_id, $seminar_id));
     if ($stmt->fetchColumn() == 0) {
         $stmt = DBManager::get()->prepare("INSERT INTO forum_entries\n                (topic_id, seminar_id, name, mkdate, chdate, lft, rgt, depth)\n                VALUES (?, ?, 'Übersicht', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 0, 1, 0)");
         $stmt->execute(array($seminar_id, $seminar_id));
     }
     // make sure, that the category "Allgemein" exists
     $stmt = DBManager::get()->prepare("INSERT IGNORE INTO forum_categories\n            (category_id, seminar_id, entry_name) VALUES (?, ?, ?)");
     $stmt->execute(array($seminar_id, $seminar_id, _('Allgemein')));
     // make sure that the default area "Allgemeine Diskussionen" exists, if there is nothing else present
     $stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries\n            WHERE seminar_id = ? AND depth = 1");
     $stmt->execute(array($seminar_id));
     // add default area
     if ($stmt->fetchColumn() == 0) {
         $data = array('topic_id' => md5(uniqid()), 'seminar_id' => $seminar_id, 'user_id' => '', 'name' => _('Allgemeine Diskussion'), 'content' => _('Hier ist Raum für allgemeine Diskussionen'), 'author' => '', 'author_host' => '');
         ForumEntry::insert($data, $seminar_id);
     }
     restoreLanguage();
 }
Exemple #9
0
 /**
  * Stores the statusgruppen of a user.
  */
 public function store_action($type, $id)
 {
     if ($type === 'institute') {
         if ($status = Request::option('status')) {
             $query = "SELECT inst_perms FROM user_inst WHERE user_id = ? AND Institut_id = ?";
             $statement = DBManager::get()->prepare($query);
             $statement->execute(array($this->user->user_id, $id));
             $perms = $statement->fetchColumn();
             if ($status != $perms && in_array($status, $this->about->allowedInstitutePerms())) {
                 $query = "UPDATE user_inst SET inst_perms = ? WHERE user_id = ? AND Institut_id = ?";
                 $statement = DBManager::get()->prepare($query);
                 $statement->execute(array($status, $this->user->user_id, $id));
                 log_event('INST_USER_STATUS', $id, $this->user->user_id, $perms . ' -> ' . $status);
                 $this->reportSuccess(_('Der Status wurde geändert!'));
             }
         }
         if ($this->shallChange('', 'institute_data')) {
             $query = "UPDATE user_inst\n                          SET raum = ?, sprechzeiten = ?, Telefon = ?, Fax = ?\n                          WHERE Institut_id = ? AND user_id = ?";
             $statement = DBManager::get()->prepare($query);
             $statement->execute(array(Request::get('raum'), Request::get('sprech'), Request::get('tel'), Request::get('fax'), $id, $this->user->user_id));
             if ($statement->rowCount() > 0) {
                 $this->reportSuccess(_('Ihre Daten an der Einrichtung %s wurden geändert.'), Request::get('name'));
                 setTempLanguage($this->user->user_id);
                 $this->postPrivateMessage(_("Ihre Daten an der Einrichtung %s wurden geändert.\n"), Request::get('name'));
                 restoreLanguage();
             }
         }
         if ($default_institute = Request::int('default_institute', 0)) {
             $query = "UPDATE user_inst SET externdefault = 0 WHERE user_id = ?";
             $statement = DBManager::get()->prepare($query);
             $statement->execute(array($this->user->user_id));
         }
         $query = "UPDATE user_inst\n                      SET externdefault = ?, visible = ?\n                      WHERE Institut_id = ? AND user_id = ?";
         $statement = DBManager::get()->prepare($query);
         $statement->execute(array($default_institute, Request::int('invisible', 0) ? 0 : 1, $id, $this->user->user_id));
     }
     if (in_array($type, words('institute role'))) {
         if ($datafields = Request::getArray('datafields')) {
             $errors = array();
             foreach ($datafields as $key => $value) {
                 $struct = new DataField($key);
                 $entry = DataFieldEntry::createDataFieldEntry($struct, array($this->user->user_id, $id));
                 $entry->setValueFromSubmit($value);
                 if ($entry->isValid()) {
                     $entry->store();
                 } else {
                     $errors[] = sprintf(_('Fehlerhafter Eintrag im Feld <em>%s</em>: %s (Eintrag wurde nicht gespeichert)'), $entry->getName(), $entry->getDisplayValue());
                 }
             }
         }
         if (!empty($errors)) {
             $this->reportErrorWithDetails(_('Bitte überprüfen Sie Ihre Eingabe.'), $errors);
         }
     }
     $this->redirect('settings/statusgruppen#' . $id);
 }
Exemple #10
0
function in_archiv ($sem_id)
{
    global $SEM_CLASS,$SEM_TYPE, $ARCHIV_PATH, $TMP_PATH, $ZIP_PATH, $ZIP_OPTIONS, $_fullname_sql;

    NotificationCenter::postNotification('CourseWillArchive', $sem_id);

    //Besorgen der Grunddaten des Seminars
    $query = "SELECT Seminar_id, Name, Untertitel, Beschreibung,
                     start_time, Institut_id, status
              FROM seminare
              WHERE Seminar_id = ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($sem_id));
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    $seminar_id     = $row['Seminar_id'];
    $name           = $row['Name'];
    $untertitel     = $row['Untertitel'];
    $beschreibung   = $row['Beschreibung'];
    $start_time     = $row['start_time'];
    $heimat_inst_id = $row['Institut_id'];

    //Besorgen von einzelnen Daten zu dem Seminar
    $semester = new SemesterData;
    $all_semester = $semester->getAllSemesterData();
    foreach ($all_semester as $sem) {
        if (($start_time >= $sem['beginn']) && ($start_time <= $sem['ende'])) {
            $semester_tmp = $sem['name'];
        }
    }

    //Studienbereiche
    if ($SEM_CLASS[$SEM_TYPE[$row['status']]['class']]['bereiche']) {
        $sem_path = get_sem_tree_path($seminar_id);
        if (is_array($sem_path)) {
            $studienbereiche = join(', ', $sem_path);
        }
    }

    // das Heimatinstitut als erstes
    $query = "SELECT Name FROM Institute WHERE Institut_id = ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($heimat_inst_id));
    $institute = $statement->fetchColumn();

    // jetzt den Rest
    $query = "SELECT Name
              FROM Institute
              LEFT JOIN seminar_inst USING (institut_id)
              WHERE seminar_id = ? AND Institute.Institut_id != ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id, $heimat_inst_id));
    while ($temp = $statement->fetchColumn()) {
        $institute .= ', ' . $temp;
    }

    $query = "SELECT GROUP_CONCAT({$_fullname_sql['full']} SEPARATOR ', ')
              FROM seminar_user
              LEFT JOIN auth_user_md5 USING (user_id)
              LEFT JOIN user_info USING (user_id)
              WHERE seminar_id = ? AND seminar_user.status = 'dozent'";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id));
    $dozenten = $statement->fetchColumn();

    $query = "SELECT fakultaets_id
              FROM seminare
              LEFT JOIN Institute USING (Institut_id)
              WHERE Seminar_id = ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id));
    $fakultaet_id = $statement->fetchColumn();

    $query = "SELECT GROUP_CONCAT(DISTINCT c.Name SEPARATOR ' | ')
              FROM seminar_inst AS a
              LEFT JOIN Institute AS b USING (Institut_id)
              LEFT JOIN Institute AS c ON (c.Institut_id = b.fakultaets_id)
              WHERE a.seminar_id = ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id));
    $fakultaet = $statement->fetchColumn();

    setTempLanguage();  // use $DEFAULT_LANGUAGE for archiv-dumps

    //Dump holen
    $dump = dump_sem($sem_id, 'nobody');

    //Forumdump holen
    foreach (PluginEngine::getPlugins('ForumModule', $sem_id) as $plugin) {
        $forumdump .= $plugin->getDump($sem_id);
    }

    // Wikidump holen
    $wikidump = getAllWikiPages($sem_id, $name, FALSE);

    restoreLanguage();

    //OK, naechster Schritt: Kopieren der Personendaten aus seminar_user in archiv_user
    $query = "INSERT INTO archiv_user (seminar_id, user_id, status)
              SELECT Seminar_id, user_id, status FROM seminar_user WHERE Seminar_id = ?";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id));

    // Eventuelle Vertretungen in der Veranstaltung haben weiterhin Zugriff mit Dozentenrechten
    if (get_config('DEPUTIES_ENABLE')) {
        $deputies = getDeputies($seminar_id);
        // Eintragen ins Archiv mit Zugriffsberechtigung "dozent"
        $query = "INSERT IGNORE INTO archiv_user SET seminar_id = ?, user_id = ?, status = 'dozent'";
        $statement = DBManager::get()->prepare($query);
        foreach ($deputies as $deputy) {
            $statement->execute(array($seminar_id, $deputy['user_id']));
        }
    }

    $Modules = new Modules;
    $Modules = $Modules->getLocalModules($sem_id);
    $folder_tree = TreeAbstract::GetInstance('StudipDocumentTree', array('range_id' => $sem_id,'entity_type' => 'sem'));

    if ($Modules['documents_folder_permissions'] || StudipDocumentTree::ExistsGroupFolders($sem_id)) {
        $unreadable_folders = $folder_tree->getUnReadableFolders('nobody');
    }

    $query = "SELECT COUNT(dokument_id) FROM dokumente WHERE seminar_id = ? AND url = ''";
    $statement = DBManager::get()->prepare($query);
    $statement->execute(array($seminar_id));
    $count = $statement->fetchColumn();
    if ($count) {
        $hash_secret = "frauen";
        $archiv_file_id = md5(uniqid($hash_secret,1));

        //temporaeres Verzeichnis anlegen
        $tmp_full_path = "$TMP_PATH/$archiv_file_id";
        mkdir($tmp_full_path, 0700);

        if($folder_tree->getNumKids('root')) {
            $list = $folder_tree->getKids('root');
        }
        if (is_array($list) && count($list) > 0) {
            $query = "SELECT folder_id, name
                      FROM folder WHERE range_id IN (?)
                      ORDER BY name";
            $statement = DBManager::get()->prepare($query);
            $statement->execute(array($list));

            $folder = 0;
            while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                $folder += 1;
                $temp_folder = $tmp_full_path . "/[$folder]_" . prepareFilename($row['name'], FALSE);
                mkdir($temp_folder, 0700);
                createTempFolder($row['folder_id'], $temp_folder, $seminar_id, 'nobody');
            }

            //zip all the stuff
            $archiv_full_path = "$ARCHIV_PATH/$archiv_file_id";
            create_zip_from_directory($tmp_full_path, $tmp_full_path);
            @rename($tmp_full_path . '.zip', $archiv_full_path);
        }
        rmdirr($tmp_full_path);

        if (is_array($unreadable_folders)) {
            $query = "SELECT dokument_id FROM dokumente WHERE seminar_id = ? AND url = '' AND range_id IN (?)";
            $statement = DBManager::get()->prepare($query);
            $statement->execute(array($seminar_id, $unreadable_folders));
            $archiv_protected_file_id = createSelectedZip($statement->fetchAll(PDO::FETCH_COLUMN), false, false);
            @rename("$TMP_PATH/$archiv_protected_file_id", "$ARCHIV_PATH/$archiv_protected_file_id");
        }
    } else {
        $archiv_file_id = '';
    }

    //Reinschreiben von diversem Klumpatsch in die Datenbank
    $query = "INSERT INTO archiv
                (seminar_id, name, untertitel, beschreibung, start_time,
                 semester, heimat_inst_id, institute, dozenten, fakultaet,
                 dump, archiv_file_id,archiv_protected_file_id, forumdump, wikidump, studienbereiche,
                 mkdate)
              VALUES
                (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, UNIX_TIMESTAMP())";
    $statement = DBManager::get()->prepare($query);
    $success = $statement->execute(array(
        $seminar_id,
        $name ?: '',
        $untertitel ?: '',
        $beschreibung ?: '',
        $start_time,
        $semester_tmp ?: '',
        $heimat_inst_id,
        $institute ?: '',
        $dozenten ?: '',
        $fakultaet ?: '',
        $dump ?: '',
        $archiv_file_id ?: '',
        $archiv_protected_file_id ?: '',
        $forumdump ?: '',
        $wikidump ?: '',
        $studienbereiche ?: '',
    ));
    if ($success) {
        NotificationCenter::postNotification('CourseDidArchive', $seminar_id);
    }
}
Exemple #11
0
 /**
  * send out the notification messages for the passed topic. The contents
  * and a link directly to the topic are added to the messages.
  * 
  * @param string $topic_id
  */
 static function notify($topic_id)
 {
     // send message to all abo-users
     $db = DBManager::get();
     $messaging = new ForumBulkMail();
     // $messaging = new Messaging();
     // get all parent topic-ids, to find out which users to notify
     $path = ForumEntry::getPathToPosting($topic_id);
     // fetch all users to notify, exlcude current user
     $stmt = $db->prepare("SELECT DISTINCT user_id\n            FROM forum_abo_users\n            WHERE topic_id IN (:topic_ids)\n                AND user_id != :user_id");
     $stmt->bindParam(':topic_ids', array_keys($path), StudipPDO::PARAM_ARRAY);
     $stmt->bindParam(':user_id', $GLOBALS['user']->id);
     $stmt->execute();
     // get details for topic
     $topic = ForumEntry::getConstraints($topic_id);
     $template_factory = new Flexi_TemplateFactory(dirname(__FILE__) . '/../views');
     $template = $template_factory->open('index/_mail_notification');
     // notify users
     while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
         $user_id = $data['user_id'];
         // create subject and content
         setTempLanguage(get_userid($user_id));
         // check if user wants an email for all or selected messages only
         $force_email = false;
         if ($messaging->user_wants_email($user_id)) {
             $force_email = true;
         }
         $parent_id = ForumEntry::getParentTopicId($topic['topic_id']);
         setTempLanguage($data['user_id']);
         $notification = sprintf(_("%s hat einen Beitrag geschrieben"), $topic['anonymous'] ? _('Anonym') : $topic['author']);
         restoreLanguage();
         PersonalNotifications::add($user_id, UrlHelper::getUrl('plugins.php/coreforum/index/index/' . $topic['topic_id'] . '#' . $topic['topic_id'], array('cid' => $topic['seminar_id']), true), $notification, "forumposting_" . $topic['topic_id'], Icon::create('forum', 'clickable')->asImagePath(40));
         if ($force_email) {
             $title = implode(' >> ', ForumEntry::getFlatPathToPosting($topic_id));
             $subject = addslashes(_('[Forum]') . ' ' . ($title ?: _('Neuer Beitrag')));
             $htmlMessage = $template->render(compact('user_id', 'topic', 'path'));
             $textMessage = trim(kill_format($htmlMessage));
             $userWantsHtml = UserConfig::get($user_id)->getValue('MAIL_AS_HTML');
             StudipMail::sendMessage(User::find($user_id)->email, $subject, addslashes($textMessage), $userWantsHtml ? $htmlMessage : null);
         }
         restoreLanguage();
     }
     $messaging->bulkSend();
 }
Exemple #12
0
 function change_course_set_action()
 {
     CSRFProtection::verifyUnsafeRequest();
     if (Request::submitted('change_course_set_assign') && Request::get('course_set_assign') && !LockRules::Check($this->course_id, 'admission_type')) {
         $cs = new CourseSet(Request::option('course_set_assign'));
         if ($cs->isUserAllowedToAssignCourse($this->user_id, $this->course_id)) {
             CourseSet::addCourseToSet($cs->getId(), $this->course_id);
             $cs->load();
             if (in_array($this->course_id, $cs->getCourses())) {
                 PageLayout::postMessage(MessageBox::success(sprintf(_("Die Zuordnung zum Anmeldeset %s wurde durchgeführt."), htmlReady($cs->getName()))));
             }
         }
     }
     if (Request::submitted('change_course_set_unassign') && !LockRules::Check($this->course_id, 'admission_type')) {
         $this->response->add_header('X-Title', _('Anmelderegeln aufheben'));
         if ($this->course->getNumWaiting() && !Request::submitted('change_course_set_unassign_yes')) {
             $question = sprintf(_("In dieser Veranstaltung existiert eine Warteliste. Die bestehende Warteliste mit %s Einträgen wird gelöscht. Sind sie sicher?"), $this->course->getNumWaiting());
         }
         $cs = CourseSet::getSetForCourse($this->course_id);
         if ($cs) {
             $priorities = AdmissionPriority::getPrioritiesByCourse($cs->getId(), $this->course_id);
             if (count($priorities) && !Request::submitted('change_course_set_unassign_yes')) {
                 $question = sprintf(_("In dieser Veranstaltung existiert eine Anmeldeliste (Losverfahren am %s). Die bestehende Anmeldeliste mit %s Einträgen wird gelöscht. Sind sie sicher?"), strftime('%x %R', $cs->getSeatDistributionTime()), count($priorities));
             }
         }
         if (!$question && $cs) {
             CourseSet::removeCourseFromSet($cs->getId(), $this->course_id);
             $cs->load();
             if (!in_array($this->course_id, $cs->getCourses())) {
                 PageLayout::postMessage(MessageBox::success(sprintf(_("Die Zuordnung zum Anmeldeset %s wurde aufgehoben."), htmlReady($cs->getName()))));
             }
             if (!count($cs->getCourses()) && $cs->isGlobal() && $cs->getUserid() != '') {
                 $cs->delete();
             }
             if ($this->course->getNumWaiting()) {
                 $num_moved = 0;
                 foreach ($this->course->admission_applicants->findBy('status', 'awaiting') as $applicant) {
                     setTempLanguage($applicant->user_id);
                     $message_body = sprintf(_('Die Warteliste der Veranstaltung **%s** wurde deaktiviert, Sie sind damit __nicht__ zugelassen worden.'), $this->course->name);
                     $message_title = sprintf(_("Statusänderung %s"), $this->course->name);
                     messaging::sendSystemMessage($applicant->user_id, $message_title, $message_body);
                     restoreLanguage();
                     $num_moved += $applicant->delete();
                 }
                 if ($num_moved) {
                     PageLayout::postMessage(MessageBox::success(sprintf(_("%s Wartende wurden entfernt."), $num_moved)));
                 }
             }
         }
     }
     if (!$question) {
         $this->redirect($this->url_for('/index'));
     } else {
         $this->request = array('change_course_set_unassign' => 1);
         $this->button_yes = 'change_course_set_unassign_yes';
         PageLayout::postMessage(MessageBox::info($question));
         $this->render_template('course/admission/_change_admission.php');
     }
 }
Exemple #13
0
 /**
  * Adds given users to the course waitlist, either at list beginning or end.
  * System messages are sent to affected users.
  *
  * @param mixed $users array of user ids to add
  * @param String $which_end 'last' or 'first': which list end to append to
  * @return mixed Array of messages (stating success and/or errors)
  */
 public function moveToWaitlist($users, $which_end)
 {
     $course = Seminar::getInstance($this->course_id);
     foreach ($users as $user_id) {
         // Delete member from seminar
         if ($course->deleteMember($user_id)) {
             setTempLanguage($user_id);
             $message = sprintf(_('Sie wurden von der Veranstaltung **%s** von ' . '%s oder der Administration abgemeldet, ' . 'Sie wurden auf die Warteliste dieser Veranstaltung gesetzt.'), $this->course_title, get_title_for_status('dozent', 1));
             restoreLanguage();
             messaging::sendSystemMessage($user_id, sprintf('%s %s', _('Systemnachricht:'), _('Anmeldung aufgehoben, auf Warteliste gesetzt')), $message);
             // Insert user in waitlist at current position.
             if ($course->addToWaitlist($user_id, $which_end)) {
                 $temp_user = User::find($user_id);
                 $msgs['success'][] = $temp_user->getFullname('no_title');
                 $curpos++;
                 // Something went wrong on removing the user from course.
             } else {
                 $msgs['error'][] = $temp_user->getFullname('no_title');
             }
             // Something went wrong on inserting the user in waitlist.
         } else {
             $msgs['error'][] = $temp_user->getFullname('no_title');
         }
     }
     return $msgs;
 }
Exemple #14
0
 /**
  * Old version of CSV import (copy and paste from teilnehmer.php
  * @return type
  * @throws AccessDeniedException
  */
 public function set_autor_csv_action()
 {
     // Security Check
     if (!$this->is_tutor) {
         throw new AccessDeniedException('Sie haben leider keine ausreichende Berechtigung, um auf diesen Bereich von Stud.IP zuzugreifen.');
     }
     CSRFProtection::verifyUnsafeRequest();
     // prepare CSV-Lines
     $messaging = new messaging();
     $csv_request = preg_split('/(\\n\\r|\\r\\n|\\n|\\r)/', trim(Request::get('csv_import')));
     $csv_mult_founds = array();
     $csv_count_insert = 0;
     $csv_count_multiple = 0;
     $datafield_id = null;
     if (Request::get('csv_import_format') && !in_array(Request::get('csv_import_format'), words('realname username'))) {
         foreach (DataField::getDataFields('user', 1 | 2 | 4 | 8, true) as $df) {
             if ($df->accessAllowed() && in_array($df->getId(), $GLOBALS['TEILNEHMER_IMPORT_DATAFIELDS']) && $df->getId() == Request::quoted('csv_import_format')) {
                 $datafield_id = $df->getId();
                 break;
             }
         }
     }
     if (Request::get('csv_import')) {
         // remove duplicate users from csv-import
         $csv_lines = array_unique($csv_request);
         $csv_count_contingent_full = 0;
         foreach ($csv_lines as $csv_line) {
             $csv_name = preg_split('/[,\\t]/', substr($csv_line, 0, 100), -1, PREG_SPLIT_NO_EMPTY);
             $csv_nachname = trim($csv_name[0]);
             $csv_vorname = trim($csv_name[1]);
             if ($csv_nachname) {
                 if (Request::quoted('csv_import_format') == 'realname') {
                     $csv_users = $this->members->getMemberByIdentification($csv_nachname, $csv_vorname);
                 } elseif (Request::quoted('csv_import_format') == 'username') {
                     $csv_users = $this->members->getMemberByUsername($csv_nachname);
                 } else {
                     $csv_users = $this->members->getMemberByDatafield($csv_nachname, $datafield_id);
                 }
             }
             // if found more then one result to given name
             if (count($csv_users) > 1) {
                 // if user have two accounts
                 $csv_count_present = 0;
                 foreach ($csv_users as $row) {
                     if ($row['is_present']) {
                         $csv_count_present++;
                     } else {
                         $csv_mult_founds[$csv_line][] = $row;
                     }
                 }
                 if (is_array($csv_mult_founds[$csv_line])) {
                     $csv_count_multiple++;
                 }
             } elseif (count($csv_users) > 0) {
                 $row = reset($csv_users);
                 if (!$row['is_present']) {
                     $consider_contingent = Request::option('consider_contingent_csv');
                     if (insert_seminar_user($this->course_id, $row['user_id'], 'autor', isset($consider_contingent), $consider_contingent)) {
                         $csv_count_insert++;
                         setTempLanguage($this->user_id);
                         $message = sprintf(_('Sie wurden in die Veranstaltung **%s** eingetragen.'), $this->course_title);
                         restoreLanguage();
                         $messaging->insert_message($message, $row['username'], '____%system%____', FALSE, FALSE, '1', FALSE, sprintf('%s %s', _('Systemnachricht:'), _('Eintragung in Veranstaltung')), TRUE);
                     } elseif (isset($consider_contingent)) {
                         $csv_count_contingent_full++;
                     }
                 } else {
                     $csv_count_present++;
                 }
             } else {
                 // not found
                 $csv_not_found[] = stripslashes($csv_nachname) . ($csv_vorname ? ', ' . stripslashes($csv_vorname) : '');
             }
         }
     }
     $selected_users = Request::getArray('selected_users');
     if (!empty($selected_users) && count($selected_users) > 0) {
         foreach ($selected_users as $selected_user) {
             if ($selected_user) {
                 if (insert_seminar_user($this->course_id, get_userid($selected_user), 'autor', isset($consider_contingent), $consider_contingent)) {
                     $csv_count_insert++;
                     setTempLanguage($this->user_id);
                     if ($GLOBALS['SEM_CLASS'][$GLOBALS['SEM_TYPE'][$_SESSION['SessSemName']['art_num']]['class']]['workgroup_mode']) {
                         $message = sprintf(_('Sie wurden manuell in die Veranstaltung **%s** eingetragen.'), $this->course_title);
                     } else {
                         $message = sprintf(_('Sie wurden manuell in die Veranstaltung **%s** eingetragen.'), $this->course_title);
                     }
                     restoreLanguage();
                     $messaging->insert_message($message, $selected_user, '____%system%____', FALSE, FALSE, '1', FALSE, sprintf('%s %s', _('Systemnachricht:'), _('Eintragung in Veranstaltung')), TRUE);
                 } elseif (isset($consider_contingent)) {
                     $csv_count_contingent_full++;
                 }
             }
         }
     }
     // no results
     if (!sizeof($csv_lines) && !sizeof($selected_users)) {
         PageLayout::postMessage(MessageBox::error(_("Niemanden gefunden!")));
     }
     if ($csv_count_insert) {
         PageLayout::postMessage(MessageBox::success(sprintf(_('%s Personen in die Veranstaltung
             eingetragen!'), $csv_count_insert)));
     }
     if ($csv_count_present) {
         PageLayout::postMessage(MessageBox::info(sprintf(_('%s Personen waren bereits in der Veranstaltung
             eingetragen!'), $csv_count_present)));
     }
     // redirect to manual assignment
     if ($csv_mult_founds) {
         PageLayout::postMessage(MessageBox::info(sprintf(_('%s Personen konnten <b>nicht eindeutig</b>
             zugeordnet werden! Nehmen Sie die Zuordnung bitte manuell vor.'), $csv_count_multiple)));
         $this->flash['csv_mult_founds'] = $csv_mult_founds;
         $this->redirect('course/members/csv_manual_assignment');
         return;
     }
     if (count($csv_not_found) > 0) {
         PageLayout::postMessage(MessageBox::error(sprintf(_('%s konnten <b>nicht</b> zugeordnet werden!'), htmlReady(join(',', $csv_not_found)))));
     }
     if ($csv_count_contingent_full) {
         PageLayout::postMessage(MessageBox::error(sprintf(_('%s Personen konnten <b>nicht</b> zugeordnet werden,
             da das ausgewählte Kontingent keine freien Plätze hat.'), $csv_count_contingent_full)));
     }
     $this->redirect('course/members/index');
 }
Exemple #15
0
/**
 * This function updates an admission procedure
 *
 * The function checks, if user could be insert to the seminar.
 * The User gets a message, if he is inserted to the seminar
 *
 * @param        string  seminar_id      the seminar_id of the seminar to calculate
 * @param        boolean send_message        should a system-message be send?
 *
 */
function normal_update_admission($seminar_id, $send_message = TRUE)
{
    $messaging=new messaging;

    //Daten holen / Abfrage ob ueberhaupt begrenzt
    $seminar = Seminar::GetInstance($seminar_id);

    if($seminar->isAdmissionEnabled()){

        $sem_preliminary = ($seminar->admission_prelim == 1);
        $cs = $seminar->getCourseSet();
        //Veranstaltung einfach auffuellen (nach Lostermin und Ende der Kontingentierung)
        if (!$seminar->admission_disable_waitlist_move && $cs->hasAlgorithmRun()) {
            //anzahl der freien Plaetze holen
            $count = (int)$seminar->getFreeAdmissionSeats();

            //Studis auswaehlen, die jetzt aufsteigen koennen
            $query = "SELECT user_id, username
                      FROM admission_seminar_user
                      LEFT JOIN auth_user_md5 USING (user_id)
                      WHERE seminar_id = ? AND status = 'awaiting'
                      ORDER BY position
                      LIMIT " . (int)$count;
            $statement = DBManager::get()->prepare($query);
            $statement->execute(array($seminar->getId()));
            $temp = $statement->fetchAll(PDO::FETCH_ASSOC);

            foreach ($temp as $row) {
                //ok, here ist the "colored-group" meant (for grouping on meine_seminare), not the grouped seminars as above!
                $group = select_group($seminar->getSemesterStartTime());

                if (!$sem_preliminary) {
                    $query = "INSERT INTO seminar_user
                                (user_id, Seminar_id, status, gruppe, mkdate)
                              VALUES (?, ?, 'autor', ?, UNIX_TIMESTAMP())";
                    $statement = DBManager::get()->prepare($query);
                    $statement->execute(array(
                        $row['user_id'],
                        $seminar->getId(),
                        $group
                    ));
                    $affected = $statement->rowCount();

                    NotificationCenter::postNotification('UserDidEnterCourse', $seminar->getId(), $row['user_id']);
                } else {
                    $query = "UPDATE admission_seminar_user
                              SET status = 'accepted'
                              WHERE user_id = ? AND seminar_id = ?";
                    $statement = DBManager::get()->prepare($query);
                    $statement->execute(array(
                        $row['user_id'],
                        $seminar->getId()
                    ));
                    $affected = $statement->rowCount();
                }
                if ($affected > 0) {
                    $log_message = 'Wurde automatisch aus der Warteliste in die Veranstaltung eingetragen.';
                    StudipLog::log('SEM_USER_ADD', $seminar->getId(), $row['user_id'], $sem_preliminary ? 'accepted' : 'autor', $log_message);
                    if (!$sem_preliminary) {
                        $query = "DELETE FROM admission_seminar_user
                                  WHERE user_id = ? AND seminar_id = ?";
                        $statement = DBManager::get()->prepare($query);
                        $statement->execute(array(
                            $row['user_id'],
                            $seminar->getId()
                        ));
                        $affected = $statement->rowCount();
                    } else {
                        $affected = 0;
                    }
                    //User benachrichtigen
                    if (($sem_preliminary || $affected > 0) && $send_message) {
                        setTempLanguage($row['user_id']);
                        if (!$sem_preliminary) {
                            $message = sprintf (_('Sie sind in die Veranstaltung **%s (%s)** eingetragen worden, da für Sie ein Platz frei geworden ist. Ab sofort finden Sie die Veranstaltung in der Übersicht Ihrer Veranstaltungen. Damit sind Sie auch für die Präsenzveranstaltung zugelassen.'), $seminar->getName(), $seminar->getFormattedTurnus(true));
                        } else {
                            $message = sprintf (_('Sie haben den Status vorläufig akzeptiert in der Veranstaltung **%s (%s)** erhalten, da für Sie ein Platz freigeworden ist.'), $seminar->getName(), $seminar->getFormattedTurnus(true));
                        }
                        $subject = sprintf(_("Teilnahme an der Veranstaltung %s"),$seminar->getName());
                        restoreLanguage();

                        $messaging->insert_message($message, $row['username'], '____%system%____', FALSE, FALSE, '1', FALSE, $subject, true);
                    }
                }
            }
            //Warteposition der restlichen User neu eintragen
            renumber_admission($seminar_id, FALSE);
        }
        $seminar->restore();
    }
}
Exemple #16
0
 /**
  * Writes a comment on a thread and outputs the metadata of new comment as json.
  * @throws AccessDeniedException
  */
 public function comment_action()
 {
     if (!Request::isPost()) {
         throw new Exception("GET not supported");
     }
     $context = Request::option("context");
     $thread = new BlubberPosting(Request::option("thread"));
     if ($thread['context_type'] === "course" && $GLOBALS['SessSemName']['class'] === "sem") {
         $seminar = new Seminar($context);
         if ($seminar->write_level > 0 && !$GLOBALS['perm']->have_studip_perm("autor", $context)) {
             throw new AccessDeniedException();
         }
     }
     BlubberPosting::$course_hashes = $thread['context_type'] === "course" ? $thread['Seminar_id'] : false;
     if (!$thread->isNew() && $thread['Seminar_id'] === $context) {
         $output = array();
         $posting = new BlubberPosting();
         $posting['context_type'] = $thread['context_type'];
         $posting['seminar_id'] = $thread['Seminar_id'];
         $posting['root_id'] = $posting['parent_id'] = $thread->getId();
         $posting['name'] = "Re: " . $thread['name'];
         if ($GLOBALS['user']->id !== "nobody") {
             $posting['user_id'] = $GLOBALS['user']->id;
         } else {
             if (Request::get("anonymous_security") === $_SESSION['blubber_anonymous_security']) {
                 $contact_user = BlubberExternalContact::findByEmail(Request::get("anonymous_email"));
                 $_SESSION['anonymous_email'] = Request::get("anonymous_email");
                 $_SESSION['anonymous_name'] = $contact_user['name'] = Request::get("anonymous_name");
                 $contact_user->store();
                 $posting['user_id'] = $contact_user->getId();
                 $posting['external_contact'] = 1;
             } else {
                 throw new AccessDeniedException("No permission to write posting.");
             }
         }
         $posting['author_host'] = $_SERVER['REMOTE_ADDR'];
         $posting['description'] = studip_utf8decode(Request::get("content"));
         $posting->store();
         BlubberPosting::$mention_posting_id = $posting->getId();
         StudipTransformFormat::addStudipMarkup("mention1", '@\\"[^\\n\\"]*\\"', null, "BlubberPosting::mention");
         StudipTransformFormat::addStudipMarkup("mention2", '@[^\\s]*[\\d\\w_]+', null, "BlubberPosting::mention");
         $content = transformBeforeSave(studip_utf8decode(Request::get("content")));
         $posting['description'] = $content;
         $posting->store();
         $factory = new Flexi_TemplateFactory($this->plugin->getPluginPath() . "/views/streams");
         $template = $factory->open("comment.php");
         $template->set_attribute('posting', $posting);
         $template->set_attribute('course_id', $thread['Seminar_id']);
         $output['content'] = $template->render($template->render());
         $output['mkdate'] = time();
         $output['posting_id'] = $posting->getId();
         //Notifications:
         $user_ids = array();
         if ($thread['user_id'] && $thread['user_id'] !== $GLOBALS['user']->id) {
             $user_ids[] = $thread['user_id'];
         }
         foreach ((array) $thread->getChildren() as $comment) {
             if ($comment['user_id'] && $comment['user_id'] !== $GLOBALS['user']->id && !$comment['external_contact']) {
                 $user_ids[] = $comment['user_id'];
             }
         }
         $user_ids = array_unique($user_ids);
         foreach ($user_ids as $user_id) {
             setTempLanguage($user_id);
             $avatar = Visibility::verify('picture', $GLOBALS['user']->id, $user_id) ? Avatar::getAvatar($GLOBALS['user']->id) : Avatar::getNobody();
             PersonalNotifications::add($user_id, PluginEngine::getURL($this->plugin, array('cid' => $thread['context_type'] === "course" ? $thread['Seminar_id'] : null), "streams/thread/" . $thread->getId()), sprintf(_("%s hat einen Kommentar geschrieben"), get_fullname()), "posting_" . $posting->getId(), $avatar->getURL(Avatar::MEDIUM));
             restoreLanguage();
         }
         $this->render_json($output);
     } else {
         $this->render_json(array('error' => "Konnte thread nicht zuordnen."));
     }
 }
 /**
  * Add the lucky ones who got a seat to the given course.
  *
  * @param Array  $user_list users to add as members
  * @param Course $course    course to add users to
  * @param int    $prio      user's priority for the given course
  */
 private function addUsersToCourse($user_list, $course, $prio = null)
 {
     $seminar = new Seminar($course->id);
     foreach ($user_list as $chosen_one) {
         setTempLanguage($chosen_one);
         $message_title = sprintf(_('Teilnahme an der Veranstaltung %s'), $seminar->getName());
         if ($seminar->admission_prelim) {
             if ($seminar->addPreliminaryMember($chosen_one)) {
                 $message_body = sprintf(_('Sie wurden für die Veranstaltung **%s** ausgelost. Die endgültige Zulassung zu der Veranstaltung ist noch von weiteren Bedingungen abhängig, die Sie bitte der Veranstaltungsbeschreibung entnehmen.'), $seminar->getName());
             }
         } else {
             if ($seminar->addMember($chosen_one, 'autor')) {
                 $message_body = sprintf(_("Sie wurden für die  Veranstaltung **%s** ausgelost. Ab sofort finden Sie die Veranstaltung in der Übersicht Ihrer Veranstaltungen. Damit sind Sie auch für die Präsenzveranstaltung zugelassen."), $seminar->getName());
             }
         }
         if ($prio) {
             $message_body .= "\n" . sprintf(_("Sie hatten für diese Veranstaltung die Priorität %s gewählt."), $prio[$chosen_one]);
         }
         messaging::sendSystemMessage($chosen_one, $message_title, $message_body);
         restoreLanguage();
     }
 }
 /**
  * Imports a line of the table into the Stud.IP database if the check returns no errors.
  * @param array $line : array of fields
  * @return array : array('found' => true|false, 'errors' => "Error message", 'pk' => "primary key")
  */
 public function importLine($line)
 {
     $plugin = $this->getPlugin();
     $classname = $this['import_type'];
     if (!$classname) {
         return array();
     }
     $data = $this->getMappedData($line);
     $pk = $this->getPrimaryKey($data);
     //Last chance to quit:
     $error = $this->checkLine($line, $data, $pk);
     $output = array();
     $object = new $classname($pk);
     if (!$object->isNew()) {
         $output['found'] = true;
         $output['pk'] = $pk;
         foreach ((array) $this['tabledata']['ignoreonupdate'] as $fieldname) {
             unset($data[$fieldname]);
         }
     } else {
         $output['found'] = false;
     }
     foreach ($data as $fieldname => $value) {
         if ($value !== false && in_array($fieldname, $this->getTargetFields())) {
             $object[$fieldname] = $value;
             if ($classname === "User" && $fieldname === "password") {
                 $object[$fieldname] = UserManagement::getPwdHasher()->HashPassword($value);
             }
         }
     }
     if (method_exists($object, "getFullName")) {
         $error['name'] = $output['name'] = $object->getFullName();
     } elseif ($object->isField("name")) {
         $error['name'] = $output['name'] = $object['name'];
     } elseif ($object->isField("title")) {
         $error['name'] = $output['name'] = $object['title'];
     }
     if ($error && $error['errors']) {
         //exit here to have the name of the object in the log
         return $error;
     }
     if ($plugin) {
         $plugin->beforeUpdate($object, $line, $data);
     }
     $object->store();
     $output['pk'] = (array) $object->getId();
     //Dynamic special fields:
     switch ($classname) {
         case "Course":
             //fleximport_dozenten
             foreach ($data['fleximport_dozenten'] as $dozent_id) {
                 $seminar = new Seminar($object->getId());
                 $seminar->addMember($dozent_id, 'dozent');
             }
             //fleximport_related_institutes
             if (!$data['fleximport_related_institutes']) {
                 $data['fleximport_related_institutes'] = array($object['institut_id']);
             } else {
                 if (!in_array($object['institut_id'], $data['fleximport_related_institutes'])) {
                     $data['fleximport_related_institutes'][] = $object['institut_id'];
                 }
             }
             foreach ($data['fleximport_related_institutes'] as $institut_id) {
                 $insert = DBManager::get()->prepare("\n                        INSERT IGNORE INTO seminar_inst\n                        SET seminar_id = :seminar_id,\n                            institut_id = :institut_id\n                    ");
                 $insert->execute(array('seminar_id' => $object->getId(), 'institut_id' => $institut_id));
             }
             if ($this['tabledata']['simplematching']["fleximport_course_userdomains"]['column'] || in_array("fleximport_course_userdomains", $this->fieldsToBeDynamicallyMapped())) {
                 $statement = DBManager::get()->prepare("\n                        SELECT userdomain_id\n                        FROM seminar_userdomains\n                        WHERE seminar_id = ?\n                    ");
                 $statement->execute(array($object->getId()));
                 $olddomains = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
                 foreach (array_diff($data['fleximport_user_inst'], $olddomains) as $to_add) {
                     $domain = new UserDomain($to_add);
                     $domain->addSeminar($object->getId());
                 }
                 foreach (array_diff($olddomains, $data['fleximport_user_inst']) as $to_remove) {
                     $domain = new UserDomain($to_remove);
                     $domain->removeSeminar($object->getId());
                 }
             }
             break;
         case "User":
             if ($this['tabledata']['simplematching']["fleximport_user_inst"]['column'] || in_array("fleximport_user_inst", $this->fieldsToBeDynamicallyMapped())) {
                 if ($object['perms'] !== "root") {
                     foreach ($data['fleximport_user_inst'] as $institut_id) {
                         $member = new InstituteMember(array($object->getId(), $institut_id));
                         $member['inst_perms'] = $object['perms'];
                         $member->store();
                     }
                 }
             }
             if ($this['tabledata']['simplematching']["fleximport_userdomains"]['column'] || in_array("fleximport_userdomains", $this->fieldsToBeDynamicallyMapped())) {
                 $olddomains = UserDomain::getUserDomainsForUser($object->getId());
                 foreach ($olddomains as $olddomain) {
                     if (!in_array($olddomain->getID(), (array) $data['fleximport_userdomains'])) {
                         $olddomain->removeUser($object->getId());
                     }
                 }
                 foreach ($data['fleximport_userdomains'] as $userdomain) {
                     $domain = new UserDomain($userdomain);
                     $domain->addUser($object->getId());
                 }
                 AutoInsert::instance()->saveUser($object->getId());
                 foreach ($data['fleximport_userdomains'] as $domain_id) {
                     if (!in_array($domain_id, $olddomains)) {
                         $welcome = FleximportConfig::get("USERDOMAIN_WELCOME_" . $domain_id);
                         if ($welcome) {
                             foreach ($object->toArray() as $field => $value) {
                                 $welcome = str_replace("{{" . $field . "}}", $value, $welcome);
                             }
                             foreach ($line as $field => $value) {
                                 $welcome = str_replace("{{" . $field . "}}", $value, $welcome);
                             }
                             if (strpos($welcome, "\n") === false) {
                                 $subject = _("Willkommen!");
                             } else {
                                 $subject = strstr($welcome, "\n", true);
                                 $welcome = substr($welcome, strpos($welcome, "\n") + 1);
                             }
                             $messaging = new messaging();
                             $count = $messaging->insert_message($welcome, $object->username, '____%system%____', null, null, null, null, $subject, true, 'normal');
                         }
                     }
                 }
             }
             if ($this['tabledata']['simplematching']["fleximport_expiration_date"]['column'] || in_array("fleximport_expiration_date", $this->fieldsToBeDynamicallyMapped())) {
                 if ($data['fleximport_expiration_date']) {
                     UserConfig::get($object->getId())->store("EXPIRATION_DATE", $data['fleximport_expiration_date']);
                 } else {
                     UserConfig::get($object->getId())->delete("EXPIRATION_DATE");
                 }
             }
             if ($output['found'] === false && $data['fleximport_welcome_message'] !== "none") {
                 $user_language = getUserLanguagePath($object->getId());
                 setTempLanguage(false, $user_language);
                 if ($data['fleximport_welcome_message'] && FleximportConfig::get($data['fleximport_welcome_message'])) {
                     $message = FleximportConfig::get($data['fleximport_welcome_message']);
                     foreach ($data as $field => $value) {
                         $message = str_replace("{{" . $field . "}}", $value, $message);
                     }
                     foreach ($line as $field => $value) {
                         if (!in_array($field, $data)) {
                             $message = str_replace("{{" . $field . "}}", $value, $message);
                         }
                     }
                     if (strpos($message, "\n") === false) {
                         $subject = dgettext($user_language, "Anmeldung Stud.IP-System");
                     } else {
                         $subject = strstr($message, "\n", true);
                         $message = substr($message, strpos($message, "\n") + 1);
                     }
                 } else {
                     $Zeit = date("H:i:s, d.m.Y", time());
                     $this->user_data = array('auth_user_md5.username' => $object['username'], 'auth_user_md5.perms' => $object['perms'], 'auth_user_md5.Vorname' => $object['vorname'], 'auth_user_md5.Nachname' => $object['nachname'], 'auth_user_md5.Email' => $object['email']);
                     $password = $data['password'];
                     //this is the not hashed password in cleartext
                     include "locale/{$user_language}/LC_MAILS/create_mail.inc.php";
                     $message = $mailbody;
                 }
                 if ($message) {
                     $mail = new StudipMail();
                     $mail->addRecipient($object['email'], $object->getFullName());
                     $mail->setSubject($subject);
                     $mail->setBodyText($message);
                     $mail->setBodyHtml(formatReady($message));
                     if (Config::get()->MAILQUEUE_ENABLE) {
                         MailQueueEntry::add($mail);
                     } else {
                         $mail->send();
                     }
                 }
                 restoreLanguage();
             }
             break;
     }
     //Datafields:
     $datafields = array();
     switch ($classname) {
         case "Course":
             $datafields = Datafield::findBySQL("object_type = 'sem'");
             break;
         case "User":
             $datafields = Datafield::findBySQL("object_type = 'user'");
             break;
         case "CourseMember":
             $datafields = Datafield::findBySQL("object_type = 'usersemdata'");
             break;
     }
     foreach ($datafields as $datafield) {
         $fieldname = $datafield['name'];
         if (isset($data[$fieldname])) {
             $entry = new DatafieldEntryModel(array($datafield->getId(), $object->getId(), ""));
             $entry['content'] = $data[$fieldname];
             $entry->store();
         }
     }
     if ($classname === "Course") {
         if ($this['tabledata']['simplematching']["fleximport_studyarea"]['column'] || in_array("fleximport_studyarea", $this->fieldsToBeDynamicallyMapped())) {
             //Studienbereiche:
             $remove = DBManager::get()->prepare("\n                    DELETE FROM seminar_sem_tree\n                    WHERE seminar_id = :seminar_id\n                ");
             $remove->execute(array('seminar_id' => $object->getId()));
             if ($GLOBALS['SEM_CLASS'][$GLOBALS['SEM_TYPE'][$data['status']]['class']]['bereiche']) {
                 foreach ($data['fleximport_studyarea'] as $sem_tree_id) {
                     $insert = DBManager::get()->prepare("\n                            INSERT IGNORE INTO seminar_sem_tree\n                            SET sem_tree_id = :sem_tree_id,\n                                seminar_id = :seminar_id\n                        ");
                     $insert->execute(array('sem_tree_id' => $sem_tree_id, 'seminar_id' => $object->getId()));
                 }
             }
         }
         if ($this['tabledata']['simplematching']["fleximport_locked"]['column'] || in_array("fleximport_locked", $this->fieldsToBeDynamicallyMapped())) {
             //Lock or unlock course
             if ($data['fleximport_locked']) {
                 CourseSet::addCourseToSet(CourseSet::getGlobalLockedAdmissionSetId(), $object->getId());
             } elseif (in_array($data['fleximport_locked'], array("0", 0)) && $data['fleximport_locked'] !== "") {
                 CourseSet::removeCourseFromSet(CourseSet::getGlobalLockedAdmissionSetId(), $object->getId());
             }
         }
         $folder_exist = DBManager::get()->prepare("\n                SELECT 1 FROM folder WHERE range_id = ?\n            ");
         $folder_exist->execute(array($object->getId()));
         if (!$folder_exist->fetch()) {
             $insert_folder = DBManager::get()->prepare("\n                    INSERT IGNORE INTO folder\n                    SET folder_id = MD5(CONCAT(:seminar_id, 'allgemeine_dateien')),\n                    range_id = :seminar_id,\n                    user_id = :user_id,\n                    name = :name,\n                    description = :description,\n                    mkdate = UNIX_TIMESTAMP(),\n                    chdate = UNIX_TIMESTAMP()\n                ");
             $insert_folder->execute(array('seminar_id' => $object->getId(), 'user_id' => $GLOBALS['user']->id, 'name' => _("Allgemeiner Dateiordner"), 'description' => _("Ablage für allgemeine Ordner und Dokumente der Veranstaltung")));
         }
     }
     if ($plugin && !$object->isNew()) {
         $plugin->afterUpdate($object, $line);
     }
     return $output;
 }
Exemple #19
0
 /**
  *
  * @param $message
  * @param $rec_uname
  * @param $user_id
  * @param $time
  * @param $tmp_message_id
  * @param $set_deleted
  * @param $signature
  * @param $subject
  * @param $force_email
  * @param $priority
  */
 function insert_message($message, $rec_uname, $user_id = '', $time = '', $tmp_message_id = '', $set_deleted = '', $signature = '', $subject = '', $force_email = '', $priority = 'normal', $tags = null)
 {
     global $user;
     $my_messaging_settings = UserConfig::get($user->id)->MESSAGING_SETTINGS;
     // wenn kein subject uebergeben
     $subject = $subject ?: _('Ohne Betreff');
     $email_request = $this->send_as_email ?: $my_messaging_settings['send_as_email'];
     // wenn keine zeit uebergeben
     $time = $time ?: time();
     // wenn keine id uebergeben
     $tmp_message_id = $tmp_message_id ?: md5(uniqid('321losgehtes', true));
     // wenn keine user_id uebergeben
     $user_id = $user_id ?: $user->id;
     # send message now
     if ($user_id != '____%system%____') {
         // real-user message
         $snd_user_id = $user_id;
         $set_deleted = $set_deleted ?: $my_messaging_settings['save_snd'] != '1';
         // don't save sms in outbox
     } else {
         // system-message
         $set_deleted = '1';
         // system-signatur
         $snd_user_id = '____%system%____';
         setTempLanguage();
         $message .= $this->sig_string;
         $message .= _('Diese Nachricht wurde automatisch vom Stud.IP-System generiert. Sie können darauf nicht antworten.');
         restoreLanguage();
     }
     // Setzen der Message-ID als Range_ID für angehängte Dateien
     if (isset($this->provisonal_attachment_id) && $GLOBALS['ENABLE_EMAIL_ATTACHMENTS']) {
         $query = "UPDATE dokumente SET range_id = ?, description = '' WHERE dokument_id = ?";
         $statement = DBManager::get()->prepare($query);
         foreach (get_message_attachments($this->provisonal_attachment_id, true) as $attachment) {
             $statement->execute(array($tmp_message_id, $attachment['dokument_id']));
         }
     }
     // insert message
     $query = "INSERT INTO message (message_id, autor_id, subject, message, priority, mkdate)\n                  VALUES (?, ?, ?, ?, ?, UNIX_TIMESTAMP())";
     $statement = DBManager::get()->prepare($query);
     $statement->execute(array($tmp_message_id, $snd_user_id, $subject, $message, $priority));
     // insert snd
     $insert_tags = DBManager::get()->prepare("\n            INSERT IGNORE INTO message_tags\n            SET message_id = :message_id,\n                user_id = :user_id,\n                tag = :tag,\n                chdate = UNIX_TIMESTAMP(),\n                mkdate = UNIX_TIMESTAMP()\n        ");
     $query = "INSERT INTO message_user (message_id, user_id, snd_rec, deleted, mkdate)\n                  VALUES (?, ?, 'snd', ?, UNIX_TIMESTAMP())";
     $statement = DBManager::get()->prepare($query);
     $statement->execute(array($tmp_message_id, $snd_user_id, $set_deleted ? 1 : 0));
     if ($tags) {
         is_array($tags) || ($tags = explode(" ", (string) $tags));
         foreach ($tags as $tag) {
             $insert_tags->execute(array('message_id' => $tmp_message_id, 'user_id' => $snd_user_id, 'tag' => strtolower($tag)));
         }
     }
     // heben wir kein array bekommen, machen wir einfach eins ...
     if (!is_array($rec_uname)) {
         $rec_uname = array($rec_uname);
     }
     // wir bastelen ein neues array, das die user_id statt des user_name enthaelt
     $rec_id = array();
     foreach ($rec_uname as $one) {
         $rec_id[] = User::findByUsername($one)->user_id;
     }
     $rec_id = array_filter($rec_id);
     // wir gehen das eben erstellt array durch und schauen, ob irgendwer was weiterleiten moechte.
     // diese user_id schreiben wir in ein tempraeres array
     foreach ($rec_id as $one) {
         $tmp_forward_id = User::find($this->get_forward_id($one))->user_id;
         if ($tmp_forward_id) {
             $rec_id[] = $tmp_forward_id;
         }
     }
     // wir mergen die eben erstellten arrays und entfernen doppelte eintraege
     $rec_id = array_unique($rec_id);
     // hier gehen wir alle empfaenger durch, schreiben das in die db und schicken eine mail
     $query = "INSERT INTO message_user (message_id, user_id, snd_rec, mkdate)\n                   VALUES (?, ?, 'rec', UNIX_TIMESTAMP())";
     $insert = DBManager::get()->prepare($query);
     $snd_name = $user_id != '____%system%____' ? User::find($user_id)->getFullName() . ' (' . User::find($user_id)->username . ')' : 'Stud.IP-System';
     foreach ($rec_id as $one) {
         $insert->execute(array($tmp_message_id, $one));
         if ($GLOBALS['MESSAGING_FORWARD_AS_EMAIL']) {
             // mail to original receiver
             $mailstatus_original = $this->user_wants_email($one);
             if ($mailstatus_original == 2 || $mailstatus_original == 3 && $email_request == 1 || $force_email) {
                 $this->sendingEmail($one, $snd_user_id, $message, $subject, $tmp_message_id);
             }
         }
         if ($tags) {
             foreach ($tags as $tag) {
                 $insert_tags->execute(array('message_id' => $tmp_message_id, 'user_id' => $one, 'tag' => strtolower($tag)));
             }
         }
     }
     // Obtain all users that should receive a notification
     $user_ids = $rec_id;
     if (is_object($GLOBALS['user'])) {
         $user_ids = array_diff($user_ids, array($GLOBALS['user']->id));
     }
     // Create notifications
     PersonalNotifications::add($user_ids, URLHelper::getUrl("dispatch.php/messages/read/{$tmp_message_id}", array('cid' => null)), sprintf(_('Sie haben eine Nachricht von %s erhalten!'), $snd_name), 'message_' . $tmp_message_id, Icon::create('mail', 'clickable')->asImagePath(80));
     return sizeof($rec_id);
 }
Exemple #20
0
 /**
  *
  **/
 public function perform($unconsumed)
 {
     $format = reset(self::$format_guesses);
     if (isset($_SERVER['CONTENT_TYPE'])) {
         foreach (self::$format_guesses as $mime_type => $guessed_format) {
             if ($_SERVER['CONTENT_TYPE'] === $mime_type) {
                 $format = $guessed_format;
             }
         }
     }
     if (preg_match('/\\.(' . implode('|', self::$format_guesses) . ')$/', $unconsumed, $match)) {
         $format = $match[1];
         $unconsumed = substr($unconsumed, 0, -strlen($match[0]));
     }
     // Get id from authorisation (either OAuth or standard)
     try {
         if (OAuth::isSigned()) {
             $user_id = OAuth::verify();
         } elseif (HTTPAuth::isSigned()) {
             $user_id = HTTPAuth::verify();
         } elseif ($GLOBALS['user']->id !== 'nobody') {
             $user_id = $GLOBALS['user']->id;
         }
         if (!$user_id) {
             throw new Exception('Unauthorized', 401);
         }
     } catch (Exception $e) {
         $status = sprintf('HTTP/1.1 %u %s', $e->getCode(), $e->getMessage());
         header($status, true, $e->getCode());
         die($status);
     }
     // Fake user identity
     $user = User::find($user_id);
     $GLOBALS['auth'] = new Seminar_Auth();
     $GLOBALS['auth']->auth = array('uid' => $user->user_id, 'uname' => $user->username, 'perm' => $user->perms);
     $GLOBALS['user'] = new Seminar_User();
     $GLOBALS['user']->fake_user = true;
     $GLOBALS['user']->register_globals = false;
     $GLOBALS['user']->start($user->user_id);
     $GLOBALS['perm'] = new Seminar_Perm();
     $GLOBALS['MAIL_VALIDATE_BOX'] = false;
     setTempLanguage($GLOBALS['user']->id);
     \Slim_Route::setDefaultConditions(array('course_id' => '[0-9a-f]{32}', 'message_id' => '[0-9a-f]{32}', 'range_id' => '[0-9a-f]{32}', 'semester_id' => '[0-9a-f]{32}', 'user_id' => '[0-9a-f]{32}'));
     $template_factory = new Flexi_TemplateFactory($this->dispatcher->plugin->getPluginPath());
     $template = $template_factory->open('app/views/api/' . $format . '.php');
     $router = RestIP\Router::getInstance(null, $template);
     $router->handleErrors();
     if (Studip\ENV === 'development') {
         error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
     } else {
         error_reporting(0);
     }
     if (Request::option('mode', 'compact') === 'complete') {
         $router->setMode(RestIP\Router::MODE_COMPLETE);
     } else {
         $router->setMode(RestIP\Router::MODE_COMPACT);
     }
     $env = $router->environment();
     $env['PATH_INFO'] = '/' . $unconsumed;
     $router->hook('slim.before.dispatch', function () use($router) {
         $route = reset($router->router()->getMatchedRoutes());
         $pattern = rtrim($route->getPattern(), '?');
         $method = strtolower(reset($route->getHttpMethods()));
         $routes = $router->getRoutes();
         $handler = $routes[$pattern][$method];
         $before = sprintf('%s::before', $handler);
         if (is_callable($before)) {
             call_user_func($before);
         }
     });
     $router->run();
     $router->hook('slim.after.dispatch', function () use($router) {
         $route = reset($router->router()->getMatchedRoutes());
         $pattern = rtrim($route->getPattern(), '?');
         $method = strtolower(reset($route->getHttpMethods()));
         $routes = $router->getRoutes();
         $handler = $routes[$pattern][$method];
         $after = sprintf('%s::after', $handler);
         if (is_callable($after)) {
             call_user_func($after);
         }
     });
     restoreLanguage();
     return new Trails_Response();
 }
Exemple #21
0
 /**
  * Stores a user's details.
  */
 public function store_action()
 {
     $this->check_ticket();
     $changed = false;
     if (Config::get()->ENABLE_SKYPE_INFO) {
         $new_skype_name = Request::get('skype_name');
         if ($new_skype_name != $this->config->SKYPE_NAME) {
             $this->config->store('SKYPE_NAME', $new_skype_name);
             Visibility::updatePrivacySettingWithTest(Request::get('skype_name'), _("Skype Name"), "skype_name", 'privatedata', 1, $this->user->user_id);
             $changed = true;
         }
         if (Request::int('skype_online_status') != $this->config->SKYPE_ONLINE_STATUS) {
             $this->config->store('SKYPE_ONLINE_STATUS', Request::int('skype_online_status'));
             Visibility::updatePrivacySettingWithTest(Request::int('skype_online_status'), _("Skype Online Status"), "skype_online_status", 'skype_name', 1, $this->user->user_id);
             $changed = true;
         }
     }
     $mapping = array('telefon' => 'privatnr', 'cell' => 'privatcell', 'anschrift' => 'privadr', 'home' => 'Home', 'motto' => 'motto', 'hobby' => 'hobby', 'lebenslauf' => 'lebenslauf', 'schwerp' => 'schwerp', 'publi' => 'publi');
     // Visibilitymapping Remove in Stud.IP 3.0 with a migration
     $vis_mapping = array('telefon' => 'private_phone', 'cell' => 'private_cell', 'anschrift' => 'privadr', 'home' => 'homepage', 'motto' => 'motto', 'hobby' => 'hobby', 'lebenslauf' => 'lebenslauf', 'schwerp' => 'schwerp', 'publi' => 'publi');
     $settingsname = array('telefon' => _('Private Telefonnummer'), 'cell' => _('Private Handynummer'), 'anschrift' => _('Private Adresse'), 'home' => _('Homepage-Adresse'), 'motto' => _('Motto'), 'hobby' => _('Hobbies'), 'lebenslauf' => _('Lebenslauf'), 'schwerp' => _('Arbeitsschwerpunkte'), 'publi' => _('Publikationen'));
     foreach ($mapping as $key => $column) {
         $value = Request::get($key);
         if (in_array($key, array('hobby', 'lebenslauf', 'schwerp', 'publi'))) {
             // purify HTML input for these fields if wysiwyg is used
             $value = Studip\Markup::purifyHtml($value);
         }
         if ($this->user->{$column} != $value && $this->shallChange('user_info.' . $column, $column, $value)) {
             $this->user->{$column} = $value;
             Visibility::updatePrivacySettingWithTest($value, $settingsname[$key], $vis_mapping[$key], 'privatedata', 1, $this->user->user_id);
             $changed = true;
         }
     }
     $datafields_changed = false;
     $errors = array();
     $datafields = DataFieldEntry::getDataFieldEntries($this->user->user_id, 'user');
     $data = Request::getArray('datafields');
     foreach ($datafields as $id => $entry) {
         if (isset($data[$id]) && $data[$id] != $entry->getValue()) {
             // i really dont know if this is correct but it works
             Visibility::updatePrivacySettingWithTest($data[$id], $entry->getName(), $entry->getID(), 'additionaldata', 1, $this->user->user_id);
             $entry->setValueFromSubmit($data[$id]);
             if ($entry->isValid()) {
                 if ($entry->store()) {
                     $datafields_changed = true;
                 }
             } else {
                 $errors[] = sprintf(_('Fehlerhafter Eintrag im Feld <em>%s</em>: %s (Eintrag wurde nicht gespeichert)'), $entry->getName(), $entry->getDisplayValue());
             }
         }
     }
     if (count($errors) > 0) {
         $this->reportErrorWithDetails(_('Bitte überprüfen Sie Ihre Eingaben.'), $errors);
     } else {
         if ($this->user->store() || $changed || $datafields_changed) {
             $this->reportSuccess(_('Daten im Lebenslauf u.a. wurden geändert.'));
             setTempLanguage($this->user->user_id);
             $this->postPrivateMessage(_('Daten im Lebenslauf u.a. wurden geändert.'));
             restoreLanguage();
         }
     }
     $this->redirect('settings/details');
 }
Exemple #22
0
 /**
  * Builds news dialog for editing / adding news
  *
  * @param string $id news           id (in case news already exists; otherwise set to "new")
  * @param string $context_range     range id (only for new news; set to 'template' for copied news)
  * @param string $template_id       template id (source of news template)
  *
  */
 function edit_news_action($id = '', $context_range = '', $template_id = '')
 {
     // initialize
     $this->news_isvisible = array('news_basic' => true, 'news_comments' => false, 'news_areas' => false);
     $ranges = array();
     $this->ranges = array();
     $this->area_options_selectable = array();
     $this->area_options_selected = array();
     $this->may_delete = false;
     $this->route = "news/edit_news/{$id}";
     if ($context_range) {
         $this->route .= "/{$context_range}";
         if ($template_id) {
             $this->route .= "/{$template_id}";
         }
     }
     $msg_object = new messaging();
     if ($id == "new") {
         unset($id);
         $this->title = _("Ankündigung erstellen");
     } else {
         $this->title = _("Ankündigung bearbeiten");
     }
     // user has to have autor permission at least
     if (!$GLOBALS['perm']->have_perm(autor)) {
         $this->set_status(401);
         return $this->render_nothing();
     }
     // Output as dialog (Ajax-Request) or as Stud.IP page?
     if (Request::isXhr()) {
         $this->set_layout(null);
         header('X-Title: ' . $this->title);
     } else {
         $this->set_layout($GLOBALS['template_factory']->open('layouts/base'));
     }
     // load news and comment data and check if user has permission to edit
     $news = new StudipNews($id);
     if (!$news->isNew()) {
         $this->comments = StudipComment::GetCommentsForObject($id);
     }
     if (!$news->havePermission('edit') and !$news->isNew()) {
         $this->set_status(401);
         PageLayout::postMessage(MessageBox::error(_('Keine Berechtigung!')));
         return $this->render_nothing();
     }
     // if form sent, get news data by post vars
     if (Request::get('news_isvisible')) {
         // visible categories, selected areas, topic, and body are utf8 encoded when sent via ajax
         $this->news_isvisible = unserialize(Request::get('news_isvisible'));
         if (Request::isXhr()) {
             $this->area_options_selected = unserialize(studip_utf8decode(Request::get('news_selected_areas')));
             $this->area_options_selectable = unserialize(studip_utf8decode(Request::get('news_selectable_areas')));
             $topic = studip_utf8decode(Request::get('news_topic'));
             $body = transformBeforeSave(Studip\Markup::purifyHtml(studip_utf8decode(Request::get('news_body'))));
         } else {
             $this->area_options_selected = unserialize(Request::get('news_selected_areas'));
             $this->area_options_selectable = unserialize(Request::get('news_selectable_areas'));
             $topic = Request::get('news_topic');
             $body = transformBeforeSave(Studip\Markup::purifyHtml(Request::get('news_body')));
         }
         $date = $this->getTimeStamp(Request::get('news_startdate'), 'start');
         $expire = $this->getTimeStamp(Request::get('news_enddate'), 'end') ? $this->getTimeStamp(Request::get('news_enddate'), 'end') - $this->getTimeStamp(Request::get('news_startdate'), 'start') : '';
         $allow_comments = Request::get('news_allow_comments') ? 1 : 0;
         if (Request::submitted('comments_status_deny')) {
             $this->anker = 'news_comments';
             $allow_comments = 0;
         } elseif (Request::submitted('comments_status_allow')) {
             $this->anker = 'news_comments';
             $allow_comments = 1;
         }
         if ($news->getValue('topic') != $topic or $news->getValue('body') != $body or $news->getValue('date') != $date or $news->getValue('allow_comments') != $allow_comments or $news->getValue('expire') != $expire) {
             $changed = true;
         }
         $news->setValue('topic', $topic);
         $news->setValue('body', $body);
         $news->setValue('date', $date);
         $news->setValue('expire', $expire);
         $news->setValue('allow_comments', $allow_comments);
     } elseif ($id) {
         // if news id given check for valid id and load ranges
         if ($news->isNew()) {
             PageLayout::postMessage(MessageBox::error(_('Die Ankündigung existiert nicht!')));
             return $this->render_nothing();
         }
         $ranges = $news->news_ranges->toArray();
     } elseif ($template_id) {
         // otherwise, load data from template
         $news_template = new StudipNews($template_id);
         if ($news_template->isNew()) {
             PageLayout::postMessage(MessageBox::error(_('Die Ankündigung existiert nicht!')));
             return $this->render_nothing();
         }
         // check for permission
         if (!$news_template->havePermission('edit')) {
             $this->set_status(401);
             return $this->render_nothing();
         }
         $ranges = $news_template->news_ranges->toArray();
         // remove those ranges for which user doesn't have permission
         foreach ($ranges as $key => $news_range) {
             if (!$news->haveRangePermission('edit', $news_range['range_id'])) {
                 $changed_areas++;
                 $this->news_isvisible['news_areas'] = true;
                 unset($ranges[$key]);
             }
         }
         if ($changed_areas == 1) {
             PageLayout::postMessage(MessageBox::info(_('1 zugeordneter Bereich wurde nicht übernommen, weil Sie dort keine Ankündigungen erstellen dürfen.')));
         } elseif ($changed_areas) {
             PageLayout::postMessage(MessageBox::info(sprintf(_('%s zugeordnete Bereiche wurden nicht übernommen, weil Sie dort keine Ankündigungen erstellen dürfen.'), $changed_areas)));
         }
         $news->setValue('topic', $news_template->getValue('topic'));
         $news->setValue('body', $news_template->getValue('body'));
         $news->setValue('date', $news_template->getValue('date'));
         $news->setValue('expire', $news_template->getValue('expire'));
         $news->setValue('allow_comments', $news_template->getValue('allow_comments'));
     } else {
         // for new news, set startdate to today and range to dialog context
         $news->setValue('date', strtotime(date('Y-m-d')));
         // + 12*60*60;
         $news->setValue('expire', 604800);
         if ($context_range != '' and $context_range != 'template') {
             $add_range = new NewsRange(array('', $context_range));
             $ranges[] = $add_range->toArray();
         }
     }
     // build news var for template
     $this->news = $news->toArray();
     // treat faculties and institutes as one area group (inst)
     foreach ($ranges as $range) {
         switch ($range['type']) {
             case 'fak':
                 $this->area_options_selected['inst'][$range['range_id']] = $range['name'];
                 break;
             default:
                 $this->area_options_selected[$range['type']][$range['range_id']] = $range['name'];
         }
     }
     // define search presets
     $this->search_presets['user'] = _('Meine Profilseite');
     if ($GLOBALS['perm']->have_perm('autor') and !$GLOBALS['perm']->have_perm('admin')) {
         $my_sem = $this->search_area('__THIS_SEMESTER__');
         if (count($my_sem['sem'])) {
             $this->search_presets['sem'] = _('Meine Veranstaltungen im aktuellen Semester') . ' (' . count($my_sem['sem']) . ')';
         }
     }
     if ($GLOBALS['perm']->have_perm('dozent') and !$GLOBALS['perm']->have_perm('root')) {
         $my_inst = $this->search_area('__MY_INSTITUTES__');
         if (count($my_inst)) {
             $this->search_presets['inst'] = _('Meine Einrichtungen') . ' (' . count($my_inst['inst']) . ')';
         }
     }
     if ($GLOBALS['perm']->have_perm('root')) {
         $this->search_presets['global'] = $this->area_structure['global']['title'];
     }
     // perform search
     if (Request::submitted('area_search') or Request::submitted('area_search_preset')) {
         $this->anker = 'news_areas';
         $this->search_term = studip_utf8decode(Request::get('area_search_term'));
         if (Request::submitted('area_search')) {
             $this->area_options_selectable = $this->search_area($this->search_term);
         } else {
             $this->current_search_preset = Request::option('search_preset');
             if ($this->current_search_preset == 'inst') {
                 $this->area_options_selectable = $my_inst;
             } elseif ($this->current_search_preset == 'sem') {
                 $this->area_options_selectable = $my_sem;
             } elseif ($this->current_search_preset == 'user') {
                 $this->area_options_selectable = array('user' => array($GLOBALS['auth']->auth['uid'] => get_fullname()));
             } elseif ($this->current_search_preset == 'global') {
                 $this->area_options_selectable = array('global' => array('studip' => _('Stud.IP')));
             }
         }
         if (!count($this->area_options_selectable)) {
             unset($this->search_term);
         } else {
             // already assigned areas won't be selectable
             foreach ($this->area_options_selected as $type => $data) {
                 foreach ($data as $id => $title) {
                     unset($this->area_options_selectable[$type][$id]);
                 }
             }
         }
     }
     // delete comment(s)
     if (Request::submitted('delete_marked_comments')) {
         $this->anker = 'news_comments';
         $this->flash['question_text'] = delete_comments(Request::optionArray('mark_comments'));
         $this->flash['question_param'] = array('mark_comments' => Request::optionArray('mark_comments'), 'delete_marked_comments' => 1);
         // reload comments
         if (!$this->flash['question_text']) {
             $this->comments = StudipComment::GetCommentsForObject($id);
             $changed = true;
         }
     }
     if ($news->havePermission('delete')) {
         $this->comments_admin = true;
     }
     if (is_array($this->comments)) {
         foreach ($this->comments as $key => $comment) {
             if (Request::submitted('news_delete_comment_' . $comment['comment_id'])) {
                 $this->anker = 'news_comments';
                 $this->flash['question_text'] = delete_comments($comment['comment_id']);
                 $this->flash['question_param'] = array('mark_comments' => array($comment['comment_id']), 'delete_marked_comments' => 1);
             }
         }
     }
     // open / close category
     foreach ($this->news_isvisible as $category => $value) {
         if (Request::submitted('toggle_' . $category) or Request::get($category . '_js')) {
             $this->news_isvisible[$category] = $this->news_isvisible[$category] ? false : true;
             $this->anker = $category;
         }
     }
     // add / remove areas
     if (Request::submitted('news_add_areas') and is_array($this->area_options_selectable)) {
         $this->anker = 'news_areas';
         foreach (Request::optionArray('area_options_selectable') as $range_id) {
             foreach ($this->area_options_selectable as $type => $data) {
                 if (isset($data[$range_id])) {
                     $this->area_options_selected[$type][$range_id] = $data[$range_id];
                     unset($this->area_options_selectable[$type][$range_id]);
                 }
             }
         }
     }
     if (Request::submitted('news_remove_areas') and is_array($this->area_options_selected)) {
         $this->anker = 'news_areas';
         foreach (Request::optionArray('area_options_selected') as $range_id) {
             foreach ($this->area_options_selected as $type => $data) {
                 if (isset($data[$range_id])) {
                     $this->area_options_selectable[$type][$range_id] = $data[$range_id];
                     unset($this->area_options_selected[$type][$range_id]);
                 }
             }
         }
     }
     // prepare to save news
     if (Request::submitted('save_news') and Request::isPost()) {
         CSRFProtection::verifySecurityToken();
         //prepare ranges array for already assigned news_ranges
         foreach ($news->getRanges() as $range_id) {
             $this->ranges[$range_id] = get_object_type($range_id, array('global', 'fak', 'inst', 'sem', 'user'));
         }
         // check if new ranges must be added
         foreach ($this->area_options_selected as $type => $area_group) {
             foreach ($area_group as $range_id => $area_title) {
                 if (!isset($this->ranges[$range_id])) {
                     if ($news->haveRangePermission('edit', $range_id)) {
                         $news->addRange($range_id);
                         $changed = true;
                     } else {
                         PageLayout::postMessage(MessageBox::error(sprintf(_('Sie haben keine Berechtigung zum Ändern der Bereichsverknüpfung für "%s".'), htmlReady($area_title))));
                         $error++;
                     }
                 }
             }
         }
         // check if assigned ranges must be removed
         foreach ($this->ranges as $range_id => $range_type) {
             if ($range_type === 'fak' && !isset($this->area_options_selected['inst'][$range_id]) || $range_type !== 'fak' && !isset($this->area_options_selected[$range_type][$range_id])) {
                 if ($news->havePermission('unassign', $range_id)) {
                     $news->deleteRange($range_id);
                     $changed = true;
                 } else {
                     PageLayout::postMessage(MessageBox::error(_('Sie haben keine Berechtigung zum Ändern der Bereichsverknüpfung.')));
                     $error++;
                 }
             }
         }
         // save news
         if ($news->validate() and !$error) {
             if ($news->getValue('user_id') != $GLOBALS['auth']->auth['uid']) {
                 $news->setValue('chdate_uid', $GLOBALS['auth']->auth['uid']);
                 setTempLanguage($news->getValue('user_id'));
                 $msg = sprintf(_('Ihre Ankündigung "%s" wurde von %s verändert.'), $news->getValue('topic'), get_fullname() . ' (' . get_username() . ')') . "\n";
                 $msg_object->insert_message($msg, get_username($news->getValue('user_id')), "____%system%____", FALSE, FALSE, "1", FALSE, _("Systemnachricht:") . " " . _("Ankündigung geändert"));
                 restoreLanguage();
             } else {
                 $news->setValue('chdate_uid', '');
             }
             $news->store();
             PageLayout::postMessage(MessageBox::success(_('Die Ankündigung wurde gespeichert.')));
             // in fallback mode redirect to edit page with proper news id
             if (!Request::isXhr() and !$id) {
                 $this->redirect('news/edit_news/' . $news->getValue('news_id'));
             } elseif (Request::isXhr()) {
                 $this->render_nothing();
             }
         }
     }
     // check if user has full permission on news object
     if ($news->havePermission('delete')) {
         $this->may_delete = true;
     }
 }
Exemple #23
0
/**
 * generates proper text for confirmation question and deletes news
 *
 *
 * @param mixed $delete_news_array (single id or array)
 * @return string text for confirmation question or empty string after deletion
 */
function delete_news($delete_news_array)
{
    $text = '';
    $confirmed = false;
    if (!is_array($delete_news_array)) {
        $delete_news_array = array($delete_news_array);
    }
    if (Request::submitted('yes') and Request::isPost()) {
        CSRFProtection::verifySecurityToken();
        $confirmed = true;
    }
    foreach ($delete_news_array as $news_id) {
        if ($news_id) {
            $delete_news = new StudipNews($news_id);
            $delete_news_titles[] = $delete_news->getValue('topic');
            if ($confirmed) {
                $msg_object = new messaging();
                if ($delete_news->havePermission('delete')) {
                    PageLayout::postMessage(MessageBox::success(sprintf(_('Ankündigung "%s" wurde gelöscht.'), htmlReady($delete_news->getValue('topic')))));
                    if ($delete_news->getValue('user_id') != $GLOBALS['auth']->auth['uid']) {
                        setTempLanguage($delete_news->getValue('user_id'));
                        $msg = sprintf(_('Ihre Ankündigung "%s" wurde von der Administration gelöscht!.'), $delete_news->getValue('topic'), get_fullname() . ' (' . get_username() . ')') . "\n";
                        $msg_object->insert_message($msg, get_username($delete_news->getValue('user_id')), "____%system%____", FALSE, FALSE, "1", FALSE, _("Systemnachricht:") . " " . _("Ankündigung geändert"));
                        restoreLanguage();
                    }
                    $delete_news->delete();
                } else {
                    PageLayout::postMessage(MessageBox::error(sprintf(_('Keine Berechtigung zum Löschen der Ankündigung "%s".'), htmlReady($delete_news->getValue('topic')))));
                }
            }
        }
    }
    if (!$confirmed) {
        if (count($delete_news_titles) == 1) {
            $text = sprintf(_('- Die Ankündigung "%s" wird unwiderruflich gelöscht.'), $delete_news_titles[0]) . "\n";
        } elseif (count($delete_news_titles) > 1) {
            $text = sprintf(_('- Die %s Ankündigungen "%s" werden unwiderruflich gelöscht.'), count($delete_news_titles), implode('", "', $delete_news_titles)) . "\n";
        }
    }
    return $text;
}
 /**
  * Executes the cronjob.
  *
  * @param mixed $last_result What the last execution of this cronjob
  *                           returned.
  * @param Array $parameters Parameters for this cronjob instance which
  *                          were defined during scheduling.
  *                          Only valid parameter at the moment is
  *                          "verbose" which toggles verbose output while
  *                          purging the cache.
  */
 public function execute($last_result, $parameters = array())
 {
     global $user;
     $cli_user = $user;
     $notification = new ModulesNotification();
     $query = "SELECT DISTINCT user_id FROM seminar_user su WHERE notification <> 0";
     if (get_config('DEPUTIES_ENABLE')) {
         $query .= " UNION SELECT DISTINCT user_id FROM deputies WHERE notification <> 0";
     }
     $rs = DBManager::get()->query($query);
     while ($r = $rs->fetch()) {
         $user = new Seminar_User($r["user_id"]);
         if ($user->locked) {
             continue;
         }
         setTempLanguage('', $user->preferred_language);
         $to = $user->email;
         $title = "[" . $GLOBALS['UNI_NAME_CLEAN'] . "] " . _("Tägliche Benachrichtigung");
         $mailmessage = $notification->getAllNotifications($user->id);
         $ok = false;
         if ($mailmessage) {
             if ($user->cfg->getValue('MAIL_AS_HTML')) {
                 $smail = new StudipMail();
                 $ok = $smail->setSubject($title)->addRecipient($to)->setBodyHtml($mailmessage['html'])->setBodyText($mailmessage['text'])->send();
             } else {
                 $ok = StudipMail::sendMessage($to, $title, $mailmessage['text']);
             }
         }
         UserConfig::set($user->id, null);
         if ($ok !== false && $parameters['verbose']) {
             echo $user->username . ':' . $ok . "\n";
         }
     }
     $user = $cli_user;
 }
Exemple #25
0
 private function sendEditMail($blubber, $subject, $message)
 {
     $messaging = new \messaging();
     setTempLanguage($blubber['user_id']);
     $messaging->insert_message($message, get_username($blubber['user_id']), $GLOBALS['user']->id, null, null, null, null, $subject);
     restoreLanguage();
 }
Exemple #26
0
 /**
  * The after filter handles the sending of private messages via email, if
  * present. Also, if an action requires the user to be logged out, this is
  * accomplished here.
  *
  * @param String $action Name of the action that has been invoked
  * @param Array  $args   Arguments of the action
  */
 public function after_filter($action, $args)
 {
     if ($this->restricted && count($this->private_messages) > 0) {
         setTempLanguage($this->user->user_id);
         $message = _("Ihre persönliche Seite wurde von Admin verändert.\n " . "Folgende Veränderungen wurden vorgenommen:\n \n") . '- ' . implode("\n- ", $this->private_messages);
         $subject = _('Systemnachricht:') . ' ' . _('Profil verändert');
         restoreLanguage();
         $messaging = new messaging();
         $messaging->insert_message($message, $this->user->username, '____%system%____', null, null, true, '', $subject);
     }
     // Check whether the user should be logged out, the token is
     // neccessary since the user could reload the page and will be logged
     // out immediately after, resulting in a login/logout-loop.
     $should_logout = $action === 'logout' && $this->flash['logout-token'] === Request::get('token');
     if ($should_logout) {
         $GLOBALS['sess']->delete();
         $GLOBALS['auth']->logout();
     }
     parent::after_filter($action, $args);
     if ($should_logout) {
         $GLOBALS['user']->set_last_action(time() - 15 * 60);
     }
 }
Exemple #27
0
    // the room-request has been resolved
    else {

        // create appropriate message
        if ($semObj->seminar_number)
            $message = sprintf (_("Ihre Raumanfrage zur Veranstaltung %s (%s) wurde bearbeitet.")." \n"._("Für folgende Belegungszeiten wurde der jeweils angegebene Raum gebucht:")."\n\n", $semObj->getName(), $semObj->seminar_number);
        else
            $message = sprintf (_("Ihre Raumanfrage zur Veranstaltung %s wurde bearbeitet.")." \n"._("Für folgende Belegungszeiten wurde der jeweils angegebene Raum gebucht:")."\n\n", $semObj->getName());

        //send the message into stud.ip message system
        // only if there are assigned dates
        if ($GLOBALS['messageForUsers'])
        {
            foreach ($users as $userid) {
                setTempLanguage($userid);
                $messaging->insert_message($message . strip_tags(str_ireplace('<br>', "\n", $GLOBALS['messageForUsers'])), get_username($userid), $user->id, FALSE, FALSE, FALSE, FALSE, _("Raumanfrage bearbeitet"), TRUE);
                restoreLanguage();
            }
        }

        //set more closed ;-)
        $reqObj->setClosed(2);
        $reqObj->store();
    }
}

//unset, if all requests are edited and the set of requests should be resetted after
if (Request::option('reset_set')) {
    unset($_SESSION['resources_data']["requests_working_on"]);
    unset($_SESSION['resources_data']["requests_open"]);
Exemple #28
0
 /**
  * Stores the account informations of a user
  */
 public function store_action()
 {
     $this->check_ticket();
     $errors = $info = $success = array();
     $logout = false;
     //erstmal die "unwichtigen" Daten
     $geschlecht = Request::int('geschlecht');
     if ($this->shallChange('user_info.geschlecht', 'gender', $geschlecht)) {
         $this->user->geschlecht = $geschlecht;
     }
     $title_front = Request::get('title_front') ?: Request::get('title_front_chooser');
     if ($this->shallChange('user_info.title_front', 'title', $title_front)) {
         $this->user->title_front = $title_front;
     }
     $title_rear = Request::get('title_rear') ?: Request::get('title_rear_chooser');
     if ($this->shallChange('user_info.title_rear', 'title', $title_rear)) {
         $this->user->title_rear = $title_rear;
     }
     if ($this->user->store()) {
         $success[] = _('Ihre persönlichen Daten wurden geändert.');
         // Inform the user about this change
         setTempLanguage($this->user->user_id);
         $this->postPrivateMessage(_("Ihre persönlichen Daten wurden geändert.\n"));
         restoreLanguage();
     }
     //nur nötig wenn der user selbst seine daten ändert
     if (!$this->restricted) {
         // Vorname verändert ?
         $vorname = trim(Request::get('vorname'));
         if ($this->shallChange('auth_user_md5.Vorname', 'name', $vorname)) {
             // Vorname nicht korrekt oder fehlend
             if (!$this->validator->ValidateName($vorname)) {
                 $errors[] = _('Der Vorname fehlt oder ist unsinnig!');
             } else {
                 $this->user->Vorname = $vorname;
                 $success[] = _('Ihr Vorname wurde geändert!');
             }
         }
         // Nachname verändert ?
         $nachname = trim(Request::get('nachname'));
         if ($this->shallChange('auth_user_md5.Nachname', 'name', $nachname)) {
             // Nachname nicht korrekt oder fehlend
             if (!$this->validator->ValidateName($nachname)) {
                 $errors[] = _('Der Nachname fehlt oder ist unsinnig!');
             } else {
                 $this->user->Nachname = $nachname;
                 $success[] = _('Ihr Nachname wurde geändert!');
             }
         }
         // Username
         $new_username = trim(Request::get('new_username'));
         if ($this->shallChange('auth_user_md5.username', 'username', $new_username)) {
             if (!$this->validator->ValidateUsername($new_username)) {
                 $errors[] = _('Der gewählte Benutzername ist nicht lang genug!');
             } else {
                 if ($check_uname = StudipAuthAbstract::CheckUsername($new_username) && $check_uname['found']) {
                     $errors[] = _('Der Benutzername wird bereits von einem anderen Benutzer verwendet. Bitte wählen Sie einen anderen Usernamen!');
                 } else {
                     $this->user->username = $new_username;
                     $success[] = _('Ihr Benutzername wurde geändert!');
                     URLHelper::addLinkParam('username', $this->user->username);
                     $logout = true;
                 }
             }
         }
         // Email
         $email1 = trim(Request::get('email1'));
         $email2 = trim(Request::get('email2'));
         if ($this->shallChange('auth_user_md5.Email', 'email', $email1)) {
             $auth = StudipAuthAbstract::GetInstance($this->user->auth_plugin ?: 'standard');
             $is_sso = $auth instanceof StudipAuthSSO;
             if (!$is_sso && !$auth->isAuthenticated($this->user->username, Request::get('password'))) {
                 $errors[] = _('Das aktuelle Passwort wurde nicht korrekt eingegeben.');
             } else {
                 if ($email1 !== $email2) {
                     $errors[] = _('Die Wiederholung der E-Mail-Adresse stimmt nicht mit Ihrer Eingabe überein.');
                 } else {
                     $result = edit_email($this->user, $email1);
                     $messages = explode('§', $result[1]);
                     if ($result[0]) {
                         $this->user->Email = $email1;
                         if (count($messages) < 2) {
                             $success[] = _('Ihre E-Mail-Adresse wurde geändert!');
                         }
                     }
                     for ($i = 0; $i < count($messages); $i += 2) {
                         $type = $messages[$i];
                         if ($type === 'msg') {
                             $type = 'success';
                         } else {
                             if ($type === 'error') {
                                 $type = 'errors';
                             }
                         }
                         ${$type}[] = $messages[$i + 1];
                     }
                 }
             }
         }
     }
     if (count($errors) > 0) {
         $this->reportErrorWithDetails(_('Bitte überprüfen Sie Ihre Eingaben:'), $errors);
     } else {
         if ($this->user->store()) {
             $this->reportSuccessWithDetails(_('Ihre Nutzerdaten wurden geändert.'), $success);
             if (count($info) > 0) {
                 $this->reportInfoWithDetails(_('Bitte beachten Sie:'), $info);
             }
         }
     }
     if ($logout) {
         $token = uniqid('logout', true);
         $this->flash['logout-token'] = $token;
         $this->redirect('settings/account/logout?token=' . $token);
     } else {
         $this->redirect('settings/account');
     }
 }