function deleteGeneric($className,$condition,&$results=false) { if($records = $this->db->getRecords(MediabirdConfig::tableName($className,true),$condition,'','id')) { $affectedIds = array(); foreach($records as $record) { $affectedIds []= intval($record->id); } $select = "id IN (".join(",",$affectedIds).")"; //delete them if($this->db->deleteRecords(MediabirdConfig::tableName($className,true),$select)) { if($results!==false) { $results['removed'.$className.'Ids'] = $affectedIds; } return true; } else { return false; } } else { //no records affected, but that's okay return true; } }
/** * Processes a logon/logout request from the client * @param $action Command that is to be performed * @param $auth Auth interface to identify the current user * @param $args Arguments for the given command * @return stdClass Object that is supposed to be sent back to the client */ function process($action, $auth, $args) { global $mediabirdDb; $reply = (object) null; switch ($action) { case "signup": $name = MediabirdUtility::getArgNoSlashes($args['name']); $password = MediabirdUtility::getArgNoSlashes($args['password']); $password = sha1(MediabirdConfig::$security_salt . $password); $email = MediabirdUtility::getArgNoSlashes($args['email']); $captcha = MediabirdUtility::getArgNoSlashes($args['captcha']); if (!MediabirdConfig::$disable_signup) { if (!MediabirdUtility::checkEmail($email)) { $reply->error = "wrongemail"; } else { if (!$captcha || $auth->getSecurityCode() != $captcha) { $auth->restartSession(); $reply->error = "wrongcaptcha"; } else { $checkIfUniqueQuery = "SELECT email,name FROM " . MediabirdConfig::tableName('User') . " WHERE email='" . $mediabirdDb->escape($email) . "' OR name='" . $mediabirdDb->escape($name) . "'"; if ($result = $mediabirdDb->getRecordSet($checkIfUniqueQuery)) { if ($mediabirdDb->recordLength($result) > 0) { //there is already a user with same email or user name $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); if ($results['email'] == $email) { $reply->error = "emailnotunique"; } else { $reply->error = "namenotunique"; } } else { if (MediabirdConfig::$disable_mail) { $hash = 1; } else { $hash = rand(2, pow(2, 24)); } $user = (object) null; $user->name = $name; $user->password = $password; $user->email = $email; $user->active = $hash; $user->created = $mediabirdDb->datetime(time()); if ($newId = $mediabirdDb->insertRecord(MediabirdConfig::tableName('User', true), $user)) { if (!MediabirdConfig::$disable_mail) { $oldReporting = error_reporting(0); $link = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "?confirmemail=" . urlencode($hash); $host = $_SERVER['SERVER_NAME']; $body = "Please confirm that you have registered the account '{$name}' at {$host} by opening the following location in your browser: {$link} . Please ignore this email if you have not issued the registration of this account. \nThank you.\n"; if (method_exists($auth, 'sendMail') && $auth->sendMail($newId, "Email confirmation for account {$name}", $body)) { $reply->success = true; $reply->mailsent = true; } else { $reply->error = "errorsending"; } error_reporting($oldReporting); } else { $reply->success = true; $reply->mailsent = false; } } else { $reply->error = "database"; } } } else { $reply->error = "database"; } } } } else { //signup disabled $reply->error = "disabled"; } break; case "confirmemail": $hash = intval($_GET['confirmemail']); if ($user = $mediabirdDb->getRecord(MediabirdConfig::tableName('User', true), "active={$hash}")) { $user->active = 1; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('User', true), $user)) { //success header("Location: ../confirmed.php?q=enabled"); return; } } header("Location: ../confirmed.php"); break; case "retrievepassword": $email = MediabirdUtility::getArgNoSlashes($args['email']); $captcha = MediabirdUtility::getArgNoSlashes($args['captcha']); if (!MediabirdConfig::$disable_mail) { if (!MediabirdUtility::checkEmail($email)) { $reply->error = "wrongemail"; } else { if (!$captcha || $auth->getSecurityCode() != $captcha) { $auth->restartSession(); $reply->error = "wrongcaptcha"; } else { $retrievePasswordQuery = "SELECT * FROM " . MediabirdConfig::tableName('User') . " WHERE email='" . $mediabirdDb->escape($email) . "'"; if (($result = $mediabirdDb->getRecordSet($retrievePasswordQuery)) && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { $name = $results['name']; $id = intval($results['id']); $password = $results['password']; $body = "You have requested a password notification.\n\nYour account is '{$name}' and the new password is '{$password}', both without the quotation marks."; $oldReporting = error_reporting(0); if (method_exists($auth, 'sendMail') && $auth->sendMail($id, "Password retrieval for Mediabird", $body)) { $reply->success = true; } else { $reply->error = "errorsending"; } error_reporting($oldReporting); } else { $reply->error = "nosuchuser"; } } } } else { //mail disabled $reply->error = "disabled"; } break; case "signin": //check user and password, retrieve $name = MediabirdUtility::getArgNoSlashes($args['name']); $password = MediabirdUtility::getArgNoSlashes($args['password']); $password = sha1(MediabirdConfig::$security_salt . $password); $logonQuery = "SELECT id,active,settings FROM " . MediabirdConfig::tableName('User') . " WHERE name='" . $mediabirdDb->escape($name) . "' AND password='******'"; $result = $mediabirdDb->getRecordSet($logonQuery); if ($result && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { if ($results['active'] == 1) { $auth->userId = intval($results['id']); //update last login $user = $mediabirdDb->getRecord(MediabirdConfig::tableName('User', true), "id={$auth->userId}"); $user->last_login = $mediabirdDb->datetime(time()); $mediabirdDb->updateRecord(MediabirdConfig::tableName('User', true), $user); //save the session info for subsequent requests $auth->createSession($auth->userId); $reply->id = $auth->userId; $reply->name = $name; $reply->settings = $results['settings']; $reply->success = true; } else { $reply->error = "disabled"; } } else { $reply->error = "passwrong"; } break; case "signout": //delete card locks associated with this user if ($auth->isAuthorized()) { $query = "SELECT id,locked_by FROM " . MediabirdConfig::tableName('Card') . " WHERE locked_by={$auth->userId}"; if ($result = $mediabirdDb->getRecordSet($query)) { while ($record = $mediabirdDb->fetchNextRecord($result)) { $record->locked_by = 0; $mediabirdDb->updateRecord(MediabirdConfig::tableName('Card', true), $record); } } if (isset($args['settings'])) { $settings = MediabirdUtility::getArgNoSlashes($args['settings']); if ($settingsJson = json_decode($settings)) { $settings = json_encode($settingsJson); $user = $mediabirdDb->getRecord(MediabirdConfig::tableName('User', true), "id={$auth->userId}"); $user->settings = $settings; $mediabirdDb->updateRecord(MediabirdConfig::tableName('User', true), $user); } } $auth->restartSession(); //notify back $reply->success = true; } break; } return $reply; }
/** * Determine changes from a given time for the given user * @param $types string[] * @param $since * @param $userId * @return MediabirdChangeInfo[] */ function getChanges($types,$since=null,$userId=null) { $changes = array(); foreach($types as $type) { if( $type==self::changeTypeCriticalItemModified || $type==self::changeTypeAnsweredItemModified || $type==self::changeTypeSolvedItemModified) { $itemTypes = array(); //determine what item types are to be matched if($type == self::changeTypeCriticalItemModified) { $itemTypes = array( self::itemTypeIssue, self::itemTypeIssueForce, self::itemTypeFeedback ); } else if($type == self::changeTypeAnsweredItemModified) { $itemTypes = array( self::itemTypeIssue, self::itemTypeIssueForce, self::itemTypeFeedback ); } else if($type == self::changeTypeSolvedItemModified) { $itemTypes = array( self::itemTypeIssueSolved, self::itemTypeFeedbackSolved ); } //create select clause $select = " modified>'".$this->db->datetime($since)."' AND question_mode IN (".join(",",$itemTypes).") AND ( user_id=$userId OR id IN ( SELECT relation_id FROM ".MediabirdConfig::tableName("Relation")." WHERE relation_type='question' AND marker_id IN ( SELECT id FROM ".MediabirdConfig::tableName("Marker")." WHERE (user_id=$userId OR shared=1) AND topic_id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." WHERE user_id=$userId AND mask>=".MediabirdTopicAccessConstants::allowViewingCards." ) ) ) ) "; $sort = 'modified DESC'; //retrieve matching records from db $questionRecords = $this->db->getRecords( MediabirdConfig::tableName('Question',true), $select, $sort ); //check if list is to be filtered by answer count if( $type == self::changeTypeCriticalItemModified || $type == self::changeTypeAnsweredItemModified) { $questionIds = array(); //collect question ids if($questionRecords) { foreach($questionRecords as $questionRecord) { $questionIds []= $questionRecord->id; } } //get answers that match if(count($questionIds)>0) { $fields = "id,question_id,user_id"; $select = "question_id IN (".join(",",$questionIds).")"; $answerRecords = $this->db->getRecords(MediabirdConfig::tableName("Answer",true),$select,$sort,$fields); } else { $answerRecords = null; } if(!$answerRecords && $type == self::changeTypeAnsweredItemModified) { continue; } //collect valid questions $validQuestionRecords = array(); foreach($questionRecords as $questionRecord) { //get question id $questionId = $questionRecord->id; //search if there is an answer record referring to that question $answerFound = false; foreach($answerRecords as $answerRecord) { if($answerRecord->question_id == $questionId) { $answerFound = true; //save reference to answer record $questionRecord->answerRecord = $answerRecord; break; } } if($type == self::changeTypeCriticalItemModified && !$answerFound) { $validQuestionRecords []= $questionRecord; } else if($type == self::changeTypeAnsweredItemModified && $answerFound) { $validQuestionRecords []= $questionRecord; } } $questionRecords = $validQuestionRecords; } //create change info for each new record foreach($questionRecords as $record) { $changeInfo = new MediabirdChangeInfo($this->name,$since,$userId); $changeInfo->itemId = $record->id; $changeInfo->itemCreated = $this->db->timestamp($record->created); $changeInfo->itemModified = $this->db->timestamp($record->modified); if(property_exists($record,"answerRecord")) { $changeInfo->itemModifier = intval($record->answerRecord->user_id); } else { $changeInfo->itemModifier = intval($record->user_id); } $changeInfo->changeType = $type; $changeInfo->itemTitle = strip_tags($record->question); $changeInfo->itemRecord = $record; $changes[$type] []= $changeInfo; } } } return $changes; }
/** * Processes a session request from the client * @param $action Command that is to be performed * @param $auth Auth interface to identify the current user * @param $args Arguments for the given command * @return stdClass Object that is supposed to be sent back to the client */ function process($action, $auth, $args) { global $mediabirdDb; $dataHandler = new MediabirdDataHandler($auth->userId); $reply = (object) null; if (isset($args['settings'])) { $settings = MediabirdUtility::getArgNoSlashes($args['settings']); $dataHandler->storeSettings($settings); } switch ($action) { case "keepAlive": //keep alive session, that's done above $reply->success = true; break; case "loadTopicList": //retrieve the topic list $query = "SELECT id FROM " . MediabirdConfig::tableName('Topic') . " WHERE user_id='{$auth->userId}'"; $infos = (array) null; if ($result = $mediabirdDb->getRecordSet($query)) { while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $id = intval($results['id']); $infos[$id] = MediabirdTopicAccessConstants::owner; } $query = "SELECT topic,mask FROM " . MediabirdConfig::tableName('Right') . " WHERE mask>0 AND group_id=ANY (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$auth->userId} AND active=1)"; if ($result = $mediabirdDb->getRecordSet($query)) { $reply->topics = (array) null; while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $id = intval($results['topic']); $mask = intval($results['mask']); if (array_key_exists($id, $infos)) { $infos[$id] = $infos[$id] | $mask; } else { $infos[$id] = $mask; } } $reply->topics = (array) null; foreach ($infos as $id => $mask) { if ($topic = $dataHandler->updateTopic($id, null, $mask, true)) { $topic->access = $mask; $reply->topics[] = $topic; } } } else { $reply->error = "database error"; error_log($query); } } else { $reply->error = "database error"; error_log($query); } $reply->success = true; break; case "checkTopicRevision": $remoteRevision = intval($args['revision']); // revision on client $topicId = intval($args['id']); if ($topic = $mediabirdDb->getRecord(MediabirdConfig::tableName('Topic', true), "id={$topicId}")) { //attempt to load topic as owner if ($topic->user_id != $auth->userId) { if ($dataHandler->getTopicRights($topicId) < MediabirdTopicAccessConstants::allowViewingCards) { $reply->error = "accessdenied"; break; } } $revision = intval($topic->revision); // revision in db if ($revision <= $remoteRevision) { $reply->success = true; //revision is up-to-date break; } else { //fall through $data = null; $ignoreContent = true; } } else { $reply->error = "database error"; break; } //fall through //fall through case "updateTopic": //update or create a topic if ($action == "updateTopic") { $data = json_decode(MediabirdUtility::getArgNoSlashes($args['topic'])); if (isset($args['id']) && is_numeric($args['id'])) { $topicId = intval(MediabirdUtility::getArgNoSlashes($args['id'])); $ignoreContent = true; } else { if (property_exists($data, "title") && property_exists($data, "category") && strlen($data->title) > 0 && strlen($data->category) > 0) { $topic = (object) null; $topic->user_id = $auth->userId; $topic->created = $mediabirdDb->datetime(time()); $topic->modified = $mediabirdDb->datetime(time()); $topic->title = '-'; if ($topicId = $mediabirdDb->insertRecord(MediabirdConfig::tableName('Topic', true), $topic)) { $ignoreContent = false; //update content for new topic } else { $reply->error = "database error"; } } else { $reply->error = "invaliddata"; } } } if (!isset($reply->error)) { //check if user is owner $query = "SELECT user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id={$topicId}"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $owner = intval($results['user_id']); $mask = 0; if ($owner != $auth->userId) { //retrieve access rights $mask = $dataHandler->getTopicRights($topicId); } else { //owner has full rights $mask = MediabirdTopicAccessConstants::owner; } if ($mask == 0) { $reply->error = "accessdenied"; } } else { $reply->error = "database error"; } } if (!isset($reply->error)) { if ($topic = $dataHandler->updateTopic($topicId, $data, $mask, $ignoreContent)) { $topic->access = $mask; $reply->success = true; if (isset($topic->reverted)) { $reply->reverted = $topic->reverted; unset($topic->reverted); } $reply->topic = $topic; } else { $reply->error = "database error"; } } break; case "updateTopicLicense": //update or create a topic $topicId = intval(MediabirdUtility::getArgNoSlashes($args['id'])); $newLicense = intval(MediabirdUtility::getArgNoSlashes($args['license'])); $query = "SELECT license,user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id={$topicId}"; if (($result = $mediabirdDb->getRecordSet($query)) && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { $license = intval($results['license']); $user = intval($results['user_id']); if ($user == $auth->userId) { if ($license != $newLicense) { $topicDb = (object) null; $topicDb->id = $topicId; $topicDb->license = $newLicense; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Topic', true), $topicDb)) { $reply->success = true; $reply->license = $newLicense; } else { $reply->error = "database error"; } } else { $reply->success = true; $reply->license = $license; } } else { $reply->error = "accessdenied"; } } else { $reply->error = "database error"; } break; case "deleteTopics": //delete a topic $topicIds = split(",", $args['ids']); foreach ($topicIds as $topicId) { //get user of topic and check if current user is owner $query = "SELECT user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id={$topicId} AND user_id={$auth->userId}"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { if ($dataHandler->deleteTopic($topicId)) { $reply->success = true; } else { unset($reply->success); $reply->error = "database error"; break; } } else { unset($reply->success); $reply->error = "accessdenied"; break; } } break; case "updateCard": //updates the contents and markers of an already registered content card $isUpdateCard = true; case "updateMarkers": //updates the personal markers of an already registered content card $cardId = intval($args['id']); if (!isset($isUpdateCard)) { $isUpdateCard = false; } //determine topic $query = "SELECT id,user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id=ANY (SELECT topic FROM " . MediabirdConfig::tableName('Card') . " WHERE id={$cardId})"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { $record = $mediabirdDb->fetchNextRecord($result); $topicId = intval($record->id); $owner = intval($record->user_id); $mask = 0; if ($owner != $auth->userId) { $mask = $dataHandler->getTopicRights($topicId); } else { $mask = MediabirdTopicAccessConstants::owner; } if ($mask == 0) { $reply->error = "accessdenied"; } } else { error_log($query); $reply->error = "accessdenied"; } if (isset($args["markers"])) { $markers = json_decode(MediabirdUtility::getArgNoSlashes($args["markers"])); } $deletedMarkerIds = array(); //default to "none deleted" if (isset($args["deletedMarkerIds"])) { $deletedMarkerIds = json_decode(MediabirdUtility::getArgNoSlashes($args["deletedMarkerIds"])); } if ($isUpdateCard) { //check for card locks $minuteAgo = $mediabirdDb->datetime(time() - 60); $query = "SELECT id FROM " . MediabirdConfig::tableName('Card') . " WHERE id={$cardId} AND (locked_by={$auth->userId} OR locked_by=0 OR locked_time < '{$minuteAgo}')"; if ($result = $mediabirdDb->getRecordSet($query)) { if ($mediabirdDb->recordLength($result) == 1) { $properties = (object) null; if (isset($args["content"])) { if ($args["content"] == "null") { $properties->content = null; } else { $content = $dataHandler->purifyHTML(MediabirdUtility::getArgNoSlashes($args["content"])); if (strlen($content) > MediabirdConstants::maxCardSize) { $reply->error = "toobig"; } else { $properties->content = $content; } } } if (isset($args["title"])) { $properties->title = MediabirdUtility::getArgNoSlashes($args["title"]); } if (isset($markers)) { $properties->markers = $markers; } } else { $reply->error = "locked"; } } else { error_log($query); $reply->error = "database error"; } } else { $properties = $markers; } if (!isset($reply->error)) { if ($isUpdateCard) { if ($card = $dataHandler->updateCard($topicId, $cardId, $properties, $mask, null, property_exists($properties, "markers"))) { if (!property_exists($properties, "markers") || is_array($card->markers = $dataHandler->updateMarkers($cardId, $properties->markers, $deletedMarkerIds, $mask, $auth->userId))) { $reply->success = true; $reply->content = $card->content; $reply->revision = $card->revision; $reply->title = $card->title; if (property_exists($card, "markers") && is_array($card->markers)) { $reply->markers = $card->markers; } } else { $reply->error = "database error"; } } else { $reply->error = "database error"; } } else { if (($markers = $dataHandler->updateMarkers($cardId, $properties, $deletedMarkerIds, $mask, $auth->userId)) !== null) { $reply->success = true; $reply->markers = $markers; $query = "SELECT revision FROM " . MediabirdConfig::tableName('Card') . " WHERE id={$cardId}"; if ($result = $mediabirdDb->getRecordSet($query)) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $revision = intval($results['revision']); $revision++; $card = (object) null; $card->id = $cardId; $card->revision = $revision; if (!$mediabirdDb->updateRecord(MediabirdConfig::tableName('Card', true), $card)) { error_log("could not increase revision of card {$cardId}"); } } else { error_log($query); } } else { $reply->error = "database error"; } } } break; case "checkCardRevision": $id = intval($args['id']); $rev = intval($args['revision']); if ($card = $mediabirdDb->getRecord(MediabirdConfig::tableName('Card', true), "id={$id}")) { $topicId = $card->topic; if ($topic = $mediabirdDb->getRecord(MediabirdConfig::tableName('Topic', true), "id={$topicId}")) { //attempt to load topic as owner if ($topic->user_id != $auth->userId) { if ($dataHandler->getTopicRights($topicId) < MediabirdTopicAccessConstants::allowViewingCards) { $reply->error = "accessdenied"; break; } } //access okay $revision = intval($card->revision); if ($revision <= $rev) { $reply->success = true; break; } else { $args['ids'] = "{$id}"; //fall through to "loadCards" } } else { $reply->error = "database error"; break; } } else { $reply->error = "database error"; break; } //fall through //fall through case "loadCards": //retrieves the contents of content cards (given by their id) $cardIds = explode(",", MediabirdUtility::getArgNoSlashes($args['ids'])); $cards = (array) null; foreach ($cardIds as $cardId) { //determine topic $query = "SELECT id,user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id=ANY (SELECT topic FROM " . MediabirdConfig::tableName('Card') . " WHERE id={$cardId})"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $topicId = intval($results['id']); $owner = intval($results['user_id']); $mask = 0; if ($owner != $auth->userId) { $mask = $dataHandler->getTopicRights($topicId); } else { $mask = MediabirdTopicAccessConstants::owner; } if ($mask == 0) { $reply->error = "accessdenied"; } } else { $reply->error = "accessdenied"; } //load content if ($card = $dataHandler->updateCard($topicId, $cardId, null, $mask)) { if (is_array($markers = $dataHandler->updateMarkers($cardId, null, array(), $mask, $auth->userId))) { $card->markers = $markers; foreach ($card->markers as $marker) { //load flash cards $query = "SELECT * FROM " . MediabirdConfig::tableName('Flashcard') . " WHERE marker={$marker->id} AND user_id={$auth->userId} ORDER BY num ASC"; $resultFlashCards = $mediabirdDb->getRecordSet($query); while ($resultsFlashCards = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($resultFlashCards))) { $flashCard = (object) null; $flashCard->marker = $marker->id; $flashCard->number = intval($resultsFlashCards['num']); $flashCard->level = intval($resultsFlashCards['level_num']); if (isset($resultsFlashCards['markedforrepetition'])) { $flashCard->markedForRepetition = intval($resultsFlashCards['markedforrepetition']); } else { $flashCard->markedForRepetition = 0; } if (isset($resultsFlashCards['lasttimeanswered'])) { $flashCard->lastTimeAnswered = intval($resultsFlashCards['lasttimeanswered']); } else { $flashCard->lastTimeAnswered = 0; } $trainingData = intval($resultsFlashCards['results']); for ($i = 0; $i < 5; $i++) { $flashCard->results[] = ($trainingData & 3 * pow(4, $i)) / pow(4, $i); } $marker->flashCards[] = $flashCard; } } $cards[] = $card; } else { $reply->error = "database error"; } } else { $reply->error = "database error"; } } if (!isset($reply->error)) { $reply->success = true; $reply->cards = $cards; } break; case "updateTrainingSession": //stores the current training session, expects a marker=>flashCards array $flashCards = json_decode(MediabirdUtility::getArgNoSlashes($args['trainingSession'])); $result = true; foreach ($flashCards as $flashCard) { $trainingResults = 0; for ($i = 0; $i < sizeof($flashCard->results); $i++) { $trainingResults |= pow(4, $i) * $flashCard->results[$i]; } if ($flashCard->number == 0) { $mediabirdDb->deleteRecords(MediabirdConfig::tableName('Flashcard', true), "marker={$flashCard->marker} AND user_id={$auth->userId}"); } $flashcard = (object) null; $flashcard->marker = $flashCard->marker; $flashcard->user_id = $auth->userId; $flashcard->num = $flashCard->number; $flashcard->level_num = $flashCard->level; $flashcard->lastTimeAnswered = $flashCard->lastTimeAnswered; $flashcard->markedForRepetition = $flashCard->markedForRepetition; $flashcard->results = $trainingResults; $result = $result && $mediabirdDb->insertRecord(MediabirdConfig::tableName('Flashcard', true), $flashcard); } if ($result) { $reply->success = true; } else { $reply->error = "database error"; } break; case "reportAbuse": //file an abuse report $id = $args['id']; $type = $args['type']; $body = "User with id {$auth->userId} has reported a violation against the Terms of Use.\nConcerned type: {$type}\nConcerned content id: {$id}\n"; if (!MediabirdConfig::$disable_mail) { $oldReporting = error_reporting(0); if (method_exists($auth, 'sendMail') && $auth->sendMail(-1, "Terms of Use violation report", $body)) { $reply->success = true; } else { $reply->error = "errorsending"; } error_reporting($oldReporting); } else { error_log("Abuse reported by user {$auth->userId} for data type {$type} and data id {$id}."); $reply->success = true; } break; case "suggestFeature": //file a suggestion $description = MediabirdUtility::getArgNoSlashes($args['description']); $body = "User with id {$auth->userId} has suggested the following feature:\n" . $description; $body = wordwrap($body, 70); if (!MediabirdConfig::$disable_mail) { $oldReporting = error_reporting(0); if (method_exists($auth, 'sendMail') && $auth->sendMail(-1, "Mediabird Feedback", $body)) { $reply->success = true; } else { $reply->error = "errorsending"; } error_reporting($oldReporting); } else { error_log("Feature suggested by user {$auth->userId}: {$description} ."); $reply->success = true; } break; case "changePass": $current = MediabirdUtility::getArgNoSlashes($args['current']); $newpass = MediabirdUtility::getArgNoSlashes($args['newpass']); if ($current == $newpass) { $reply->success = true; } else { if ($user = $mediabirdDb->getRecord(MediabirdConfig::tableName("User", true), "id={$auth->userId}")) { if ($user->password == $current) { $user->password = $newpass; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName("User", true), $user)) { $reply->success = true; } } else { $reply->error = "wrongpass"; } } } break; case "deleteAccount": //delete the current account $current = MediabirdUtility::getArgNoSlashes($args['current']); $query = "SELECT email,name FROM " . MediabirdConfig::tableName('User') . " WHERE id={$auth->userId} AND password='******'"; $result = $mediabirdDb->getRecordSet($query); if ($result && $mediabirdDb->recordLength($result) == 1) { //fetch user info $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $name = $results['name']; $email = $results['email']; //delete user $result = $mediabirdDb->deleteRecords(MediabirdConfig::tableName('User', true), "id={$auth->userId} AND password='******'"); //also delete topics $query = "SELECT id FROM " . MediabirdConfig::tableName('Topic') . " WHERE user_id={$auth->userId}"; $result = $mediabirdDb->getRecordSet($query); if ($result) { while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $topicId = $results['id']; $dataHandler->deleteTopic($topicId); } } $userfolder = ".MediabirdConfig::{$uploads_folder}." . $auth->userId . DIRECTORY_SEPARATOR; if (file_exists($userfolder)) { $oldReporting = error_reporting(0); MediabirdUtility::deleteFolder($userfolder); error_reporting($oldReporting); } //notify user $body = "Your account '{$name}' has been deleted and all associated personal data has been erased.\nWe hope you enjoyed using Mediabird. You are welcome back anytime.\nYour Mediabird team."; if (!MediabirdConfig::$disable_mail) { $oldReporting = error_reporting(0); if (method_exists($auth, 'sendMail') && $auth->sendMail($email, "Account cancelled", $body)) { $reply->success = true; } else { $reply->error = "errorsending"; } error_reporting($oldReporting); } //restart session! $auth->restartSession(); $reply->success = true; } else { $reply->error = "wrongpass"; } break; case "checkOutCard": //checks out a card for editing $cardid = intval($args['id']); $minuteAgo = $mediabirdDb->datetime(time() - 60); $select = "id={$cardid} AND (locked_by IN (0,{$auth->userId}) OR locked_time < '{$minuteAgo}')"; if ($card = $mediabirdDb->getRecord(MediabirdConfig::tableName('Card', true), $select)) { $topicId = $card->topic; if ($topic = $mediabirdDb->getRecord(MediabirdConfig::tableName('Topic', true), "id={$topicId}")) { //attempt to load topic as owner if ($topic->user_id != $auth->userId) { if ($dataHandler->getTopicRights($topicId) < MediabirdTopicAccessConstants::allowViewingCards) { $reply->error = "accessdenied"; break; } } //access okay $reply->revision = intval($card->revision); $card->locked_by = $auth->userId; $card->locked_time = $mediabirdDb->datetime(time()); if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Card', true), $card)) { $reply->success = true; } else { error_log("could not update card " . print_r($card, true)); $reply->error = "database error"; } } else { $reply->error = "database error"; } } else { $reply->error = "locked"; } break; case "checkInCard": //releases a content card lock $cardid = intval($args['id']); if ($card = $mediabirdDb->getRecord(MediabirdConfig::tableName('Card', true), "id={$cardid} AND locked_by={$auth->userId}")) { $card->locked_by = 0; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Card', true), $card)) { $reply->success = true; } else { $reply->error = "database error"; } } else { $reply->error = "database error"; } break; case "loadNotifications": //feed.title, feed.message_type $query = "SELECT id, object_id, object_type, user_id, feed_id FROM " . MediabirdConfig::tableName('FeedMessage') . "\n\t\t\t\tfeed_id = ANY (SELECT feed_id FROM " . MediabirdConfig::tableName('FeedSubscription') . " WHERE user_id={$auth->userId}) AND user_id = ANY\n\t\t\t\t\t(SELECT user_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE active=1 AND user_id <> {$auth->userId} AND group_id = ANY\n\t\t\t\t\t (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE active=1 AND user_id <> {$auth->userId})\n\t\t\t\t\t ) AND message.id NOT IN \n\t\t\t\t\t ( SELECT message_id FROM " . MediabirdConfig::tableName('FeedMessagesStatus') . " WHERE user_id={$auth->userId} AND status=1 )\n\t\t\t\t\t GROUP BY id"; if ($result = $mediabirdDb->getRecordSet($query)) { $feedMessages = (array) null; while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $feedMessage = (object) null; $feedMessage->id = intval($results['id']); $feedMessage->feedId = intval($results['feed_id']); $feedMessage->objectId = intval($results['object_id']); $feedMessage->objectType = intval($results['object_type']); $feedMessage->userId = intval($results['user_id']); $feedMessages[] = $feedMessage; } //collect feed ids $feedIds = array(); foreach ($feedMessages as $feedMessage) { if (!in_array($feedMessage->feedId, $feedIds)) { array_push($feedIds, $feedMessage->feedId); } } if ($records = $mediabirdDb->getRecords(MediabirdConfig::tableName('Feed', true), "id IN (" . join(",", $feedIds) . ")", '', "id,title,message_type")) { foreach ($feedMessages as $fi => $feedMessage) { foreach ($records as $record) { if ($record->id == $feedMessage->feedId) { $feedMessage->messageType = $record->message_type; $feedMessage->feedTitle = $record->title; $feedMessages[$fi] = $feedMessage; break; } } } } $reply->notifications = $feedMessages; $reply->success = true; } else { error_log($query); $reply->error = "database error"; } break; case "markNotificationAsRead": $id = intval($args['id']); //check if $id valid $query = "SELECT id,status FROM " . MediabirdConfig::tableName('FeedMessagesStatus') . " WHERE user_id={$auth->userId} AND message_id={$id} "; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { if ($results = $mediabirdDb->fetchNextRecord($result)) { $statusId = intval($results->id); $statusStatus = intval($results->status); if ($statusStatus != 1) { $messagesStatus = (object) null; $messagesStatus->id = $statusId; $messagesStatus->status = 1; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('FeedMessagesStatus', true), $messagesStatus)) { $reply->success = true; } else { error_log($query); $reply->error = "database error"; } } else { $reply->success = true; } } else { error_log($query); $reply->error = "database error"; } } else { $feedDB = (object) null; $feedDB->message_id = $id; $feedDB->status = 1; $feedDB->user_id = $auth->userId; if ($mediabirdDb->insertRecord(MediabirdConfig::tableName('FeedMessagesStatus', true), $feedDB)) { $reply->success = true; } else { error_log($query); $reply->error = "database error"; } } break; case "getCardsWithMarker": $type = $args['tool']; $select = "id IN (\n\t\t\t\t\tSELECT card FROM " . MediabirdConfig::tableName('Marker') . " WHERE notify>0 AND tool='" . $mediabirdDb->escape($type) . "' \n\t\t\t\t\t\tAND (shared = 1 OR user_id = {$auth->userId})\n\t\t\t\t\t)\n\t\t\t\t\tAND (\n\t\t\t\t\t\ttopic IN (\n\t\t\t\t\t\t\tSELECT id FROM " . MediabirdConfig::tableName('Topic') . " WHERE user_id={$auth->userId}\n\t\t\t\t\t\t)\n\t\t\t\t\t\tOR\n\t\t\t\t\t\ttopic IN (\n\t\t\t\t\t\t\tSELECT topic FROM " . MediabirdConfig::tableName('Right') . " WHERE group_id IN (\n\t\t\t\t\t\t\t\tSELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$auth->userId} AND active=1\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t)"; $cards = (array) null; if ($results = $mediabirdDb->getRecords(MediabirdConfig::tableName('Card', true), $select, 'created DESC', 'id')) { foreach ($results as $result) { $card = (object) null; $card->id = intval($result->id); $cards[] = $card; } } $reply->cards = $cards; $reply->success = true; break; case "loadGroups": $referredUsers = (array) null; //retrieve all groups where current user is member and public groups $query = "SELECT * FROM " . MediabirdConfig::tableName('Group') . " WHERE id=ANY (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$auth->userId}) OR access_num>0"; $reply->groups = (array) null; if ($result = $mediabirdDb->getRecordSet($query)) { while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $group = (object) null; $group->id = intval($results['id']); $group->name = $results['name']; $group->category = $results['category']; $group->description = $results['description']; $group->access = intval($results['access_num']); //check for own membership $query = "SELECT level_num,active FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$group->id} AND user_id={$auth->userId}"; if (($resultMember = $mediabirdDb->getRecordSet($query)) && ($results = $mediabirdDb->fetchNextRecord($resultMember))) { $memberMe = (object) null; $memberMe->user = $auth->userId; $memberMe->enabled = intval($results->active); $memberMe->level = intval($results->level_num); $group->members[] = $memberMe; } //retrieve all members! $query = "SELECT user_id,level_num,active FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$group->id} AND user_id<>{$auth->userId}"; if (!isset($memberMe) || $memberMe->enabled != 1 && $memberMe->enabled != 3) { //if not member of group or (requested or invited by a member) -> only show active members, hide invitees and requesters $query .= " AND active=1"; } if ($resultMembers = $mediabirdDb->getRecordSet($query)) { while ($resultsMember = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($resultMembers))) { $member = (object) null; $member->user = intval($resultsMember['user_id']); if (array_search($member->user, $referredUsers) === false) { $referredUsers[] = $member->user; } $member->enabled = intval($resultsMember['active']); $member->level = intval($resultsMember['level_num']); $group->members[] = $member; } } $reply->groups[] = $group; } } else { $reply->error = "database error"; error_log($query); } $users = (array) null; if (count($referredUsers) > 0) { $query = "SELECT id,name,email FROM " . MediabirdConfig::tableName('User') . " WHERE id IN (" . join(",", $referredUsers) . ")"; if ($result = $mediabirdDb->getRecordSet($query)) { while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $userInfo = (object) null; $userInfo->id = intval($results['id']); $userInfo->name = $results['name']; $userInfo->email = $results['email']; $users[] = $userInfo; } $reply->success = true; } else { $reply->error = "database error"; error_log($query); } } else { $reply->success = true; } $reply->userNames = $users; if (isset($args['includeKnown']) && method_exists($auth, 'getKnownUsers')) { $externalUsersTemp = $auth->getKnownUsers(); $externalUsers = array(); foreach ($externalUsersTemp as $externalTemp) { $found = false; if (property_exists($externalTemp, 'mb_id')) { foreach ($users as $user) { if ($user->id == $externalTemp->mb_id) { $found = true; } } } if (!$found) { array_push($externalUsers, $externalTemp); } } $reply->externalUsers = $externalUsers; } break; case "updateGroup": $groupId = intval(MediabirdUtility::getArgNoSlashes($args['id'])); $properties = json_decode(MediabirdUtility::getArgNoSlashes($args['group'])); //check for own membership $query = "SELECT level_num,active FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id={$auth->userId}"; $memberMe = (object) null; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1 && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { if (intval($results['level_num']) >= MediabirdConstants::groupLevelAdmin) { //we are admin and allowed to change it $groupDB = (object) null; $groupDB->access_num = $properties->access; $groupDB->name = $properties->name; $groupDB->category = $properties->category; $groupDB->description = $properties->description; $groupDB->modified = $mediabirdDb->datetime(time()); $groupDB->id = $groupId; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Group', true), $groupDB)) { $reply->access = intval($properties->access); $reply->name = $properties->name; $reply->category = $properties->category; $reply->description = $properties->description; $reply->success = true; } } else { $reply->error = "norights"; } } else { $reply->error = "database error"; } break; case "createGroup": $group_raw = json_decode(MediabirdUtility::getArgNoSlashes($args['group'])); $group = (object) null; $group->name = $group_raw->name; $group->description = $group_raw->description; $group->category = $group_raw->category; $group->type = 0; $group->access_num = $group_raw->access; $group->created = $mediabirdDb->datetime(time()); $group->modified = $mediabirdDb->datetime(time()); if ($id = $mediabirdDb->insertRecord(MediabirdConfig::tableName('Group', true), $group)) { $group->id = intval($id); $group->access = $group->access_num; unset($group->access_num); unset($group->created); unset($group->modified); //create membership with admin level $membershipDB = (object) null; $membershipDB->group_id = $group->id; $membershipDB->user_id = $auth->userId; $membershipDB->level_num = MediabirdConstants::groupLevelAdmin; $membershipDB->active = 1; $membershipDB->created = $mediabirdDb->datetime(time()); $membershipDB->modified = $mediabirdDb->datetime(time()); if ($id = $mediabirdDb->insertRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { $membership = (object) null; $membership->id = intval($id); $membership->enabled = $membershipDB->active; $membership->level = $membershipDB->level_num; $membership->user = $membershipDB->user_id; $group->members[] = $membership; $reply->success = true; $reply->group = $group; } else { error_log("membership"); $reply->error = "database error"; } } else { error_log("group"); $reply->error = "database error"; } break; case "inviteToGroup": $groupId = intval(MediabirdUtility::getArgNoSlashes($args['group'])); //users identifyable by id, i.e. mediabird members if (isset($args['ids']) && strlen($args['ids']) > 0) { $ids = MediabirdUtility::getArgNoSlashes($args['ids']); $ids = split(",", $ids); } else { $ids = (array) null; } if (isset($args['names']) && strlen($args['names']) > 0) { $emails = MediabirdUtility::getArgNoSlashes($args['names']); $emails = split(",", $emails); } else { $emails = (array) null; } //array containing users that have just been invited $unknownInvitees = (array) null; if (isset($args['externalIds']) && strlen($args['externalIds']) > 0 && method_exists($auth, 'inviteKnownUser')) { $externalIds = MediabirdUtility::getArgNoSlashes($args['externalIds']); //users known from a mediabird embedding plattform $externalIds = split(",", $externalIds); $inviteeUnknown = false; // variable to receive a value whether the user is already using Mediabird or not foreach ($externalIds as $eId) { if ($internalId = $auth->inviteKnownUser($eId, $inviteeUnknown)) { if ($inviteeUnknown) { array_push($unknownInvitees, $internalId); } array_push($ids, $internalId); } } } if (count($ids) > 0 || count($emails) > 0) { //check for own membership $query = "SELECT level_num,active FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id={$auth->userId}"; $memberMe = (object) null; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1 && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { $memberMe->user = $auth->userId; $memberMe->enabled = intval($results['active']); $memberMe->level = intval($results['level_num']); } //check for invite rights $query = "SELECT access_num FROM " . MediabirdConfig::tableName('Group') . " WHERE id={$groupId}"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1 && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { if (isset($memberMe) && $memberMe->level >= MediabirdConstants::groupLevelAdmin || intval($results['access_num']) > 0) { //current user is admin or group is public if (count($ids) != 0) { foreach ($ids as $i => $id) { $ids[$i] = intval($id); } } if (count($emails) > 0) { foreach ($emails as $i => $email) { if (MediabirdUtility::checkEmail($email)) { //checks if email has a valid format $query = "SELECT id FROM " . MediabirdConfig::tableName('User') . " WHERE email='" . $mediabirdDb->escape($email) . "'"; if ($result = $mediabirdDb->getRecordSet($query)) { if ($results = $mediabirdDb->fetchNextRecord($result)) { $emailUserId = intval($results->id); if (array_search($emailUserId, $ids) === false) { $ids[] = $emailUserId; } } else { if (!method_exists($auth, "inviteUser")) { if (!property_exists($reply, "notfound")) { $reply->notfound = (array) null; } $reply->notfound[] = $email; } else { // users unknown to the system are invited per mail here // using the auth interface to allow for external email invitation $mailSuccess = $auth->inviteUser($email); if ($mailSuccess) { $ids[] = $mailSuccess; $unknownInvitees[] = $mailSuccess; } else { $reply->notfound[] = $email; } } } } } } } //find valid ids $query = "SELECT id FROM " . MediabirdConfig::tableName('User') . " WHERE id<>{$auth->userId} AND "; if (count($ids) > 0) { $query .= "id IN (" . join(",", $ids) . ")"; } else { $query .= "0=1"; } if ($result = $mediabirdDb->getRecordSet($query)) { while ($results = $mediabirdDb->fetchNextRecord($result)) { $inviteId = intval($results->id); //check if user is already member of group $select = "user_id={$inviteId} AND group_id={$groupId}"; if (!$mediabirdDb->getRecord(MediabirdConfig::tableName('Membership', true), $select)) { if ($memberMe->level >= MediabirdConstants::groupLevelAdmin) { if (in_array($inviteId, $unknownInvitees)) { // if user has just been invited to Mediabird, a full membership is created // new user will be able to find shared topic when having logged in $enabled = 1; } else { $enabled = 3; } } else { $enabled = 2; } $membershipDB = (object) null; $membershipDB->user_id = $inviteId; $membershipDB->group_id = $groupId; $membershipDB->active = $enabled; $membershipDB->created = $mediabirdDb->datetime(time()); $membershipDB->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->insertRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { if (!property_exists($reply, "invited")) { $reply->invited = (array) null; } $reply->invited[] = $inviteId; } else { $reply->error = "database error"; } } } } else { error_log($query); $reply->error = "database error"; } if (!isset($reply->error)) { $reply->success = true; } } else { $reply->error = "norights"; } } else { error_log($query); $reply->error = "database error"; } } else { $reply->state = "emptylist"; } break; case "joinGroup": $groupId = intval(MediabirdUtility::getArgNoSlashes($args['id'])); //test if already joined $query = "SELECT id,active FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$auth->userId} AND group_id={$groupId}"; if ($result = $mediabirdDb->getRecordSet($query)) { $resultssCount = $mediabirdDb->recordLength($result); $enabled = 0; if ($resultssCount > 0 && ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)))) { $memberId = intval($results['id']); $enabled = intval($results['active']); $reply->state = $enabled; } if ($resultssCount == 0 || $enabled >= 2) { //not a member or was invited //check if user is allowed to join or request, or confirm invitation $query = "SELECT access_num FROM " . MediabirdConfig::tableName('Group') . " WHERE id={$groupId}"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $access = intval($results['access_num']); //enabled = 3 means was invited by admin if ($enabled != 3 && $access == 0) { //access denied! $reply->error = "access denied"; } else { if ($resultssCount == 0) { //request if ($access == 1) { $enabled = 0; } else { $enabled = 1; } $membershipDB = (object) null; $membershipDB->user_id = $auth->userId; $membershipDB->group_id = $groupId; $membershipDB->active = $enabled; $membershipDB->created = $mediabirdDb->datetime(time()); $membershipDB->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->insertRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { $reply->state = $enabled; } $reply->created = true; } else { //confirm invitation if ($enabled == 3 || $access > 1) { $enabled = 1; } else { $enabled = 0; } $membership = (object) null; $membership->id = $memberId; $membership->active = $enabled; $membership->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Membership', true), $membership)) { $reply->state = $enabled; } } } } } } if (property_exists($reply, "state")) { $reply->success = true; } else { if (!isset($reply->error)) { $reply->error = "database error"; } } break; case "updateMember": //promote, accept or remove member $groupId = intval(MediabirdUtility::getArgNoSlashes($args['group'])); $memberUserId = intval(MediabirdUtility::getArgNoSlashes($args['user'])); $level = intval(MediabirdUtility::getArgNoSlashes($args['level'])); $enabled = intval(MediabirdUtility::getArgNoSlashes($args['enabled'])); //check if user has admin rights $query = "SELECT id FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id={$auth->userId} AND (level_num >= " . MediabirdConstants::groupLevelAdmin . ")"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { if ($memberUserId != $auth->userId) { if ($level != -1) { //check if there is a user that can be promoted $membershipDB = $mediabirdDb->getRecord(MediabirdConfig::tableName('Membership', true), "group_id={$groupId} AND user_id={$memberUserId} AND active=0"); $membershipDB->level_num = $level; $membershipDB->active = $enabled; $membershipDB->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { $reply->success = true; $reply->level = $level; $reply->enabled = $enabled; } else { $reply->error = "nomember"; } } else { if ($dataHandler->deleteMembership($memberUserId, $groupId)) { $reply->success = true; $reply->level = -1; } else { $reply->error = "database error"; } } } else { if ($level == -1) { $reply->error = "cannotremoveownmembership"; } else { //only allow demoting oneself if there is at least one other admin! $query = "SELECT FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id<>{$auth->userId} AND (level_num >= " . MediabirdConstants::groupLevelAdmin . ")"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) > 0) { //demoting allowed $membershipDB = $mediabirdDb->getRecord(MediabirdConfig::tableName('Membership', true), "group_id={$groupId} AND user_id={$memberUserId}"); $membershipDB->level_num = $level; $membershipDB->active = $enabled; $membershipDB->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { $reply->success = true; $reply->level = $level; $reply->enabled = $enabled; } else { $reply->error = "database error"; } } else { $reply->error = "notenoughadmins"; } } } } else { $reply->error = "norights"; } break; case "leaveGroup": $groupId = intval(MediabirdUtility::getArgNoSlashes($args['id'])); //check for further admins $query = "SELECT user_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND (level_num >= " . MediabirdConstants::groupLevelAdmin . ")"; if ($result = $mediabirdDb->getRecordSet($query)) { $removeMembership = true; if ($mediabirdDb->recordLength($result) == 1) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); if (intval($results['user_id']) == $auth->userId) { //user is only admin of group, promote to next member $query = "SELECT id FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id <> {$auth->userId}"; if ($result = $mediabirdDb->getRecordSet($query)) { if ($mediabirdDb->recordLength($result) > 0) { if ($membershipDB = $mediabirdDb->getRecord(MediabirdConfig::tableName('Membership', true), "group_id={$groupId} AND user_id <> {$auth->userId} AND active=1")) { $membershipDB->level_num = MediabirdConstants::groupLevelAdmin; $membershipDB->modified = $mediabirdDb->datetime(time()); if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Membership', true), $membershipDB)) { $reply->state = "foundnewadmin"; } else { $removeMembership = false; } } else { $removeMembership = false; } } else { //no user left, delete group! if ($dataHandler->deleteGroup($groupId)) { $reply->state = "groupremoved"; } else { $removeMembership = false; } } } else { $removeMembership = false; } } } if ($removeMembership) { if ($dataHandler->deleteMembership($auth->userId, $groupId)) { $reply->success = true; } else { $reply->error = "database error"; } } else { $reply->error = "nonewadmin"; } } else { $reply->error = "database error"; } break; case "shareTopic": $topicId = intval(MediabirdUtility::getArgNoSlashes($args['topic'])); $groupId = intval(MediabirdUtility::getArgNoSlashes($args['group'])); $mask = intval(MediabirdUtility::getArgNoSlashes($args['mask'])); //check if user is owner of topic $query = "SELECT user_id FROM " . MediabirdConfig::tableName('Topic') . " WHERE id={$topicId}"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { $result = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $owner = intval($result['user_id']); if ($owner == $auth->userId) { //check if user is member of group $query = "SELECT id FROM " . MediabirdConfig::tableName('Membership') . " WHERE group_id={$groupId} AND user_id={$auth->userId} AND active=1"; if (($result = $mediabirdDb->getRecordSet($query)) && $mediabirdDb->recordLength($result) == 1) { //user is member of group, check if already shared $query = "SELECT id,mask FROM " . MediabirdConfig::tableName('Right') . " WHERE topic={$topicId} AND group_id={$groupId}"; if ($result = $mediabirdDb->getRecordSet($query)) { if ($mediabirdDb->recordLength($result) == 0) { //share $right = (object) null; $right->topic = $topicId; $right->group_id = $groupId; $right->mask = $mask; if ($rightId = $mediabirdDb->insertRecord(MediabirdConfig::tableName('Right', true), $right)) { $reply->mask = $mask; $reply->id = $rightId; $reply->success = true; } else { $reply->error = "database error"; } } else { if ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $reply->id = intval($results['id']); $reply->mask = $mask; $currentMask = intval($results['mask']); if ($currentMask != $mask) { $rightDB = (object) null; $rightDB->id = $reply->id; $rightDB->mask = $mask; if ($mediabirdDb->updateRecord(MediabirdConfig::tableName('Right', true), $rightDB)) { $reply->success = true; } else { $reply->error = "database error"; } } else { $reply->success = true; } } else { $reply->error = "database error"; } } } else { $reply->error = "database error"; } } else { $reply->error = "notmember"; } } else { $reply->error = "notowner"; } } break; case "searchDatabase": $query = MediabirdUtility::getArgNoSlashes($args['query']); $type = intval($args['type']); if ($results = $dataHandler->searchDatabase($query, $type)) { $reply->groups = $results[0]; $reply->topics = $results[1]; $reply->cards = $results[2]; $reply->success = true; } else { $reply->error = "database error"; } break; case "checkEquationSupport": $reply->exists = class_exists("LatexRender", false) && file_exists(MediabirdConfig::$latex_path) && file_exists(MediabirdConfig::$convert_path); break; case "renderEquation": if (class_exists("LatexRender") && isset($args["topic"]) && isset($args["equation"])) { $topic = intval($args["topic"]); if (MediabirdUtility::checkAccess($topic, $auth->userId)) { $userFolder = MediabirdConfig::$uploads_folder; if (property_exists($auth, "userSubfolder")) { $userFolder .= $auth->userSubfolder . DIRECTORY_SEPARATOR; } else { $userFolder .= $auth->userId . DIRECTORY_SEPARATOR; } if (!file_exists($userFolder)) { mkdir($userFolder, 0777, true); } $userQuota = MediabirdUtility::getUserQuota($auth->userId); $quotaLeft = MediabirdUtility::quotaLeft($auth->userId, $userQuota); $equation = MediabirdUtility::getArgNoSlashes($args["equation"]); $renderer = new LatexRender($userFolder, "", MediabirdConfig::$cache_folder); $renderer->_latex_path = MediabirdConfig::$latex_path; $renderer->_convert_path = MediabirdConfig::$convert_path; $resultFile = $renderer->checkFormulaCache($equation); if (!$resultFile) { $resultFile = $renderer->renderLatex($equation); if ($resultFile && file_exists($resultFile)) { $fileSize = filesize($resultFile); if ($fileSize < $quotaLeft || $quotaLeft == -1) { $status_code = copy($resultFile, $renderer->destinationFile); if (!$status_code) { $resultFile = null; $renderer->_errorcode = 6; } else { $resultFile = $renderer->destinationFile; } } else { $resultFile = null; $renderer->_errorcode = 7; //not enough quota } $renderer->cleanTemporaryDirectory(); } else { $renderer->_errorcode = 3; //could not render file } } else { $resultFile = $userFolder . $resultFile; } $reply = (object) null; if ($resultFile && file_exists($resultFile)) { $resultFile = str_ireplace(MediabirdConfig::$uploads_folder, '', $resultFile); $resultFile = str_replace(DIRECTORY_SEPARATOR, '/', $resultFile); $reply->success = true; $reply->topic = $topic; $reply->filename = $resultFile; } else { $reply->errorcode = $renderer->_errorcode; $reply->error = "latex"; } } else { $reply->error = "invalidtopic"; } } break; } return $reply; }
function load($data,&$results) { if(!isset($data)) { $data = array(); } $fromTime = isset($data['contents']['fromTime']) ? $data['contents']['fromTime'] : 0; $loadedIds = isset($data['contents']['loadedIds']) ? array_values($data['contents']['loadedIds']) : array(); $ids = isset($data['contents']['restrictIds']) ? array_values($data['contents']['restrictIds']) : array(); $avoidIds = isset($data['contents']['avoidIds']) ? array_values($data['contents']['avoidIds']) : array(); $parentIds = isset($data['contents']['parentIds']) ? array_values($data['contents']['parentIds']) : array(); $select = "topic_id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName('Right')." WHERE mask>=".MediabirdTopicAccessConstants::allowViewingCards." AND user_id=$this->userId )"; if(count($ids)>0) { $select = "card_id IN (".join(",",$ids).") AND (".$select.")"; } else if(count($parentIds)>0) { $select = "topic_id IN (".join(",",$parentIds).") AND (".$select.")"; } if(count($avoidIds)>0) { $select = "card_id NOT IN (".join(",",$avoidIds).") AND ".$select; } //if no loaded ids are given, save time by including modified condition into sql query if($fromTime > 0 && count($loadedIds)==0) { $select = "modified>'".$this->db->datetime($fromTime)."' AND $select"; } $contents = array(); $cards = array(); $cardIds = array(); if($records = $this->db->getRecords(MediabirdConfig::tableName('CardContent',true),$select)) { foreach($records as $record) { //determine card id $content = (object)null; $content->id = intval($record->card_id); //override global from time with individual settings if given if(isset($data['contents'][$content->id])) { $fromTime = $data['contents'][$content->id]; } MediabirdUtility::arrayRemove($loadedIds,$content->id); $content->modified = $this->db->timestamp($record->modified); if($content->modified>$fromTime) { $content->content = $record->content; $contents []= $content; } } } if(count($contents)>0) { $results['contents'] = $contents; } if(count($loadedIds)>0) { $results['removedContentIds'] = $loadedIds; } return true; }
$portal_user_item->save(); } } $commsy_user_id = $portal_user_item->getItemID(); $fullname = $portal_user_item->getFullname(); $pic_url = $portal_user_item->getPictureUrl(true,false); unset($portal_user_item); unset($current_user_item); $mbuser = $external_id_manager->getExternalId($system,$commsy_user_id); if ( !empty($mbuser) ) { //load last login info before it will be updated if($userRecord = $mediabirdDb->getRecord(MediabirdConfig::tableName('User',true),"id=$mbuser")) { //get last login time $lastLogin = $mediabirdDb->timestamp($userRecord->last_login); //save login time $_SESSION['mb_session_time'] = $lastLogin; } $helper->updateUser($mbuser,$fullname,1,null, $pic_url, $mediabirdDb); } else { $mbuser = $helper->registerUser($fullname,1,null, $pic_url, $mediabirdDb); if ( !empty($mbuser) ) { $external_id_manager->addIDsToDB($system,$mbuser,$commsy_user_id); } else { include_once('functions/error_functions.php'); trigger_error('can not initiate mediabird account',E_USER_ERROR); }
function updateSettings($settings,&$results) { //fixme: validate this (define what is allowed in here first) $userRecord = (object)array( 'id'=>$this->userId, 'settings'=>json_encode($settings) ); if($this->db->updateRecord(MediabirdConfig::tableName("User",true),$userRecord)) { $results['settings'] = $settings; return true; } else { return false; } }
public function getDetailActionAsHTML () { $retour = ''; $current_user = $this->_environment->getCurrentUserItem(); if ( $this->_environment->inPrivateRoom() ) { $own_room = $this->_environment->getCurrentContextItem(); } else { $own_room = $current_user->getOwnRoom(); } if ( isset($own_room) and !$current_user->isOnlyReadUser() ) { $system = 'mediabird'; $url_params = array(); $url_params['name'] = $system; $url_params['SID'] = $this->_environment->getSessionID(); include_once('functions/security_functions.php'); $url_params['security_token'] = getToken(); $url_params['output'] = 'pure'; $plugin_folder = 'plugins'; $plugin_name = '/mediabird'; $plugin_dir = $plugin_folder.$plugin_name; $commsyUrl = $this->_getContentLink(); include_once($plugin_dir.'/config/config_default.php'); include($plugin_dir.'/config/config.php'); include_once($plugin_dir.'/server/helper.php'); include_once($plugin_dir.'/server/utility.php'); include_once($plugin_dir.'/server/dbo.php'); include_once($plugin_dir.'/server/db_mysql.php'); global $mediabirdDb; $mediabirdDb = new MediabirdDboMySql(); $helper = new MediabirdHtmlHelper(); $userId = $this->_getMBUserID(); if($mediabirdDb->connect()) { $relatedNotes = $helper->findRelatedNotes($commsyUrl,$userId,$mediabirdDb); $title = $this->_translator->getMessage('MEDIABIRD_ACTION_ICON_USER_TITLE'); if($relatedNotes && count($relatedNotes[0])>0) { // there are own notices $card_id = $relatedNotes[0][0]; $img = ucfirst($this->_translator->getMessage('MEDIABIRD_ACTION_NAME_DETAIL')).' ('.count($relatedNotes[0]).')'; } else { //no related notes yet $img = ucfirst($this->_translator->getMessage('MEDIABIRD_ACTION_NAME_DETAIL')); //determine the card the user's been to most recently if(isset($userId) && ($sessionRecord = $mediabirdDb->getRecord(MediabirdConfig::tableName("Session",true),"user_id=$userId"))) { $card_id = $sessionRecord->card_id; } } $mediabirdDb->disconnect(); } else { $title = $this->_translator->getMessage('MEDIABIRD_ACTION_ICON_USER_TITLE'); $img = ucfirst($this->_translator->getMessage('MEDIABIRD_ACTION_NAME_DETAIL')); } $retour = '<a href="javascript:void(0)" id="mediabirdLink" title="'.$title.'">'.$img.'</a>'.LF; $frameUrl = _curl(false,$this->_environment->getCurrentContextID(),$system,'index',$url_params); $frameUrl .= "&mb_url=".urlencode($commsyUrl); if ( !empty( $card_id ) ) { $frameUrl .= "&mb_card_id=".urlencode($card_id); } $titleHtml = '<div class="title">'.$this->_translator->getMessage('MEDIABIRD_OVERLAY_TITLE').'</div>'; $retour .= '<div id="mediabirdOverlay" class="mediabird-overlay">'.LF; $retour .= ' <div class="bar"><a href="javascript:void(0)" class="closer">X</a><a href="javascript:void(0)" class="expander expanded"></a>'.$titleHtml.'</div>'.LF; $retour .= ' <div class="resize-handle right"></div>'.LF; $retour .= ' <div class="resize-handle"></div>'.LF; $retour .= ' <iframe src="" frameborder="no" scrolling="no" id="mediabirdFrame">'.LF; $retour .= ' </iframe>'.LF; $retour .= '</div>'.LF; $retour .= '<script type="text/javascript" src="'.$plugin_dir.'/js/overlay.js"></script>'.LF; $retour .= '<link rel="stylesheet" href="'.$plugin_dir.'/css/overlay_commsy.php?cid='.$this->_environment->getCurrentContextID().'"/>'.LF; $retour .= '<script type="text/javascript">'.LF; $retour .= '//<![CDATA['.LF; $retour .= ' mbOverlay.MAX_HEIGHT = 544;'.LF; $retour .= ' mbOverlay.MAX_WIDTH = 685;'.LF; $retour .= ' mbOverlay.SIZE_SECURE = 34;'.LF; $retour .= ' var url = "'.$frameUrl.'";'.LF; $retour .= ' mbOverlay.doIframe(url,document.getElementById("mediabirdLink"),document.getElementById("mediabirdOverlay"),{width:685,height:544},document.getElementById("mediabirdFrame"));'.LF; $retour .= '//]]>'.LF; $retour .= '</script>'.LF; } elseif ( $current_user->isOnlyReadUser() ) { $title = $this->_translator->getMessage('COMMON_NO_ACTION_NEW',$this->_translator->getMessage('MEDIABIRD_OVERLAY_TITLE')); $img = '<img src="'.$this->getActionNotActiveIcon().'" style="vertical-align:bottom;" title="'.$title.'"/>'; $retour = $img.LF; } else { $title = $this->_translator->getMessage('MEDIABIRD_ACTION_ICON_NOT_ACTIVE_TITLE'); $img = '<img src="'.$this->getActionNotActiveIcon().'" style="vertical-align:bottom;" title="'.$title.'"/>'; $retour = $img.LF; } return $retour; }
function delete($id) { $deleteLinkQuery = "id=$id"; $result = $this->db->deleteRecords(MediabirdConfig::tableName('Link',true),$deleteLinkQuery); return $result; }
function signout($args) { $results = array(); //delete card locks associated with this user if ($this->auth->isAuthorized()) { $query="SELECT id,locked_by FROM ".MediabirdConfig::tableName('Content')." WHERE locked_by=$this->userId"; if ($result = $this->db->getRecordSet($query)) { while($record = $this->db->fetchNextRecord($result)) { $record->locked_by = 0; $this->db->updateRecord(MediabirdConfig::tableName('Content',true),$record); } } if ( property_exists($args,'settings')) { $settings = MediabirdUtility::getArgNoSlashes($args->settings); if ($settingsJson = json_decode($settings)) { $settings = json_encode($settingsJson); $user = $this->db->getRecord(MediabirdConfig::tableName('User',true),"id=$this->userId"); $user->settings = $settings; $this->db->updateRecord(MediabirdConfig::tableName('User',true),$user); } } $this->auth->restartSession(); //notify back $results['r'] = MediabirdConstants::processed; } return $results; }
function delete($ids,&$results) { //check if user is owner of upload $select = "id IN (".join(",",$ids).") AND user_id=$this->userId"; if($this->db->countRecords(MediabirdConfig::tableName("Upload",true),$select) != count($ids)) { return MediabirdConstants::accessDenied; } //now delete upload and cards featuring that file //detemine all cards that feature the file $select = "content_type=1 AND content_id IN (".join(",",$ids).")"; $okay = true; if($cardRecords = $this->db->getRecords(MediabirdConfig::tableName("Card",true),$select)) { //collect their ids $cardIds = array(); foreach($cardRecords as $cardRecord) { $cardIds []= intval($cardRecord->id); } $results['removedCardIds'] = $cardIds; //prepare delete statements $cardIdString = join(",",$cardIds); $select = "marker_id IN (SELECT id FROM ".MediabirdConfig::tableName('Marker')." WHERE card_id IN ($cardIdString))"; $okay = $okay && parent::deleteGeneric('Relation',$select,$results); $select = "card_id IN ($cardIdString)"; $okay = $okay && parent::deleteGeneric('CardTag',$select); $select = "card_id IN ($cardIdString)"; $okay = $okay && parent::deleteGeneric('Marker',$select,$results); $select = "id IN ($cardIdString)"; $okay = $okay && parent::deleteGeneric('Card',$select,$results); } $select = "id IN (".join(",",$ids).")"; $okay = $okay && parent::deleteGeneric('Upload',$select,$results); if($okay) { return MediabirdConstants::processed; } else { return MediabirdConstants::serverError; } }
function load($data,&$results) { $tagColors = array(); //get existing tag color records $select = "user_id=$this->userId"; if($tagColorRecords = $this->db->getRecords(MediabirdConfig::tableName('TagColor',true),$select)) { foreach($tagColorRecords as $tagColorRecord) { $tagColor = (object)null; $tagColor->tagId = intval($tagColorRecord->tag_id); $tagColor->userColor = strtoupper($tagColorRecord->color); $tagColor->showText = intval($tagColorRecord->display_text); array_push($tagColors,$tagColor); } } $results['tagColors'] = $tagColors; return true; }
/** * Send's an anonymous email to some address, preferably the Mediabird team or a user * @param $to Mediabird id of user to which to deliver email * @param $subject Subject of email * @param $body Body of email * @return bool Success */ function sendMail($to,$subject,$body) { if(!MediabirdConfig::$disable_mail) { $address=null; $cc = ''; if($to==-1) { $address=MediabirdConfig::$webmaster_address; if ( !empty(MediabirdConfig::$developer_address) ) { $cc = MediabirdConfig::$developer_address; } } else { $query="SELECT `email` FROM ".MediabirdConfig::tableName('User')." WHERE `id`=$to"; if($result=mysql_query($query)) { $row=mysql_fetch_row($result); $address=$row[0]; } } if(isset($address)) { $headers = "From: ".MediabirdConfig::$no_reply_address."\r\n". "Reply-To: ".MediabirdConfig::$no_reply_address."\r\n". "X-Mailer: PHP/".phpversion(); if ( !empty($cc) ) { $headers .= "\r\n"."Cc: ".$cc; } return mail($address, $subject, $body, $headers); } } return false; }
/** * Determines marker ids and card ids of markers related to a given set of object ids */ function findMarkers($data,$relationType,&$results) { $validates = is_object($data) && MediabirdUtility::checkKeyset($data,$this->findMarkerParams,true) && is_array($data->ids); if($validates) { foreach($data->ids as $id) { if(!is_int($id)) { $validates = false; break; } } } if($validates) { //enough validation! $select = "id IN ( SELECT marker_id FROM ".MediabirdConfig::tableName("Relation")." WHERE relation_type='".$relationType."' AND relation_id IN (".join(",",$data->ids).") ) AND ( user_id=$this->userId OR (shared=1 AND topic_id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." WHERE user_id=$this->userId AND mask>=".MediabirdTopicAccessConstants::allowViewingCards." )) )"; //array to store infos about the markers $markerInfos = array(); //now get all related markers $markerRecords = $this->db->getRecords(MediabirdConfig::tableName("Marker",true),$select,'','id,card_id'); if($markerRecords) { foreach($markerRecords as $markerRecord) { $markerInfo = (object)array( 'id'=>intval($markerRecord->id), 'cardId'=>intval($markerRecord->card_id) ); $markerInfos []= $markerInfo; } } if(isset($results['markerInfos'])) { $results['markerInfos'] = array_merge($results['markerInfos'],$markerInfos); } else { $results['markerInfos'] = $markerInfos; } return true; } else { $results['r'] = MediabirdConstants::invalidData; return false; } }
/** * Determine changes from a given time for the given user * @param $types string[] * @param $since * @param $userId * @return MediabirdChangeInfo[] */ function getChanges($types,$since=null,$userId=null) { $changes = array(); foreach($types as $type) { if($type==self::changeTypeRightCreation) { //create select clause $select = "user_id=$userId AND created>'".$this->db->datetime($since)."'"; //retrieve matching records from db $records = $this->db->getRecords( MediabirdConfig::tableName('Right',true), $select, 'modified DESC' ); //create change info for each new record foreach($records as $record) { //get topic record $select = "id=".$record->topic_id; $topicRecord = $this->db->getRecord(MediabirdConfig::tableName('Topic',true),$select); if($topicRecord) { $changeInfo = new MediabirdChangeInfo($this->name,$since,$userId); $changeInfo->itemId = $record->id; $changeInfo->itemCreated = $this->db->timestamp($record->created); $changeInfo->itemModified = $this->db->timestamp($record->modified); $changeInfo->changeType = self::changeTypeRightCreation; $changeInfo->itemId = $record->id; $changeInfo->itemTitle = $topicRecord->title; $changeInfo->itemModifier = intval($topicRecord->modifier); $changeInfo->record = $record; $changes[self::changeTypeRightCreation] []= $changeInfo; } } } else if($type==self::changeTypeTopicChange) { //create select clause $select = "modified>'".$this->db->datetime($since)."' AND id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." WHERE user_id=$userId AND mask>=".MediabirdTopicAccessConstants::allowViewingCards." )"; //retrieve matching records from db $records = $this->db->getRecords( MediabirdConfig::tableName('Topic',true), $select, 'modified DESC' ); //create change info for each new record foreach($records as $record) { $changeInfo = new MediabirdChangeInfo($this->name,$since,$userId); $changeInfo->itemId = $record->id; $changeInfo->itemCreated = $this->db->timestamp($record->created); $changeInfo->itemModified = $this->db->timestamp($record->modified); $changeInfo->itemModifier = intval($record->modifier); $changeInfo->changeType = self::changeTypeTopicChange; $changeInfo->itemId = $record->id; $changeInfo->itemTitle = $record->title; $changeInfo->itemRecord = $record; $changes[self::changeTypeTopicChange][]= $changeInfo; } } } return $changes; }
<?php MediabirdConfig::$database_table_prefix = $CFG->prefix; $tableNames = MediabirdConfig::$table_names; //database adjustments foreach ($tableNames as $key => $value) { $tableNames[$key] = 'studynotes_' . $value; } MediabirdConfig::$table_names = $tableNames; MediabirdConfig::$database_name = null;
/** * Searches the database for a specific query and return topics and groups who match it * @return Array First element: groups found, second: topics found. Null on error * @param $needle String */ function searchDatabase($needle, $type) { global $mediabirdDb; //remove non-alpha $needle = preg_replace("/[^ 0-9a-zA-Zßäöüéèáà\\-_]/i", '', $needle); $needle = preg_replace("/[ ]+/i", ' ', $needle); $exps = split(" ", $needle); //prepare result arrays $topics = (array) null; $groups = (array) null; $cards = (array) null; //determine accessible groups $accessibleGroups = array(); $minAccess = 3; //only search groups the user is member of if (strlen($needle) > 0) { if ($type == MediabirdSearchType::group) { //user is looking for a specific group $minAccess = 1; } else { //user is looking for specific content, only show easily accessible one $minAccess = 2; } } $query = "SELECT id FROM " . MediabirdConfig::tableName('Group') . " WHERE id IN (SELECT id FROM " . MediabirdConfig::tableName('Group') . " WHERE access_num>={$minAccess}) OR id IN (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$this->userId} AND active IN (1,3))"; if ($result = $mediabirdDb->getRecordSet($query)) { //collect ids while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $accessibleGroups[] = intval($results['id']); } } else { error_log($query); return null; } if ($type & MediabirdSearchType::topic || $type & MediabirdSearchType::card) { //find all topics which are accessible $query = "SELECT id FROM " . MediabirdConfig::tableName('Topic') . " WHERE user_id={$this->userId}"; if (count($accessibleGroups) > 0) { $query .= " OR id=ANY\n\t\t\t(SELECT topic FROM " . MediabirdConfig::tableName('Right') . " WHERE mask > 1\n\t\t\t\t\t\t\t\tAND group_id IN (" . join(",", $accessibleGroups) . ")\n\t\t\t\t\t\t\t)"; } $topicIds = (array) null; if ($result = $mediabirdDb->getRecordSet($query)) { //collect ids while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $topicIds[] = intval($results['id']); } } else { error_log($query); return null; } if ($type & MediabirdSearchType::topic && count($topicIds) > 0) { //select those whose title match the query $query = "SELECT id,title,category FROM " . MediabirdConfig::tableName('Topic') . " WHERE id IN (" . join(",", $topicIds) . ") AND (\n\t\t\t\t" . $this->__likeOr("title", $exps) . " OR\n\t\t\t\t" . $this->__likeOr("category", $exps) . "\n\t\t\t\t)\n\t\t\t\tORDER BY modified DESC"; if ($result = $mediabirdDb->getRecordSet($query, null, 10)) { //collect ids while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $topic = (object) null; $topic->id = intval($results['id']); $topic->group = $this->getPublicTopicGroup($topic->id); $topic->title = $results['title']; $topic->category = $results['category']; $topics[] = $topic; array_splice($topicIds, array_search($topic->id, $topicIds), 1); } } else { error_log($query); return null; } } if (count($topicIds) > 0) { //from the remainder, select those whose cards match the query $query = "SELECT id,topic,title FROM " . MediabirdConfig::tableName('Card') . "\n\t\t\t\tWHERE topic IN (" . join(",", $topicIds) . ") AND (\n\t\t\t\t" . $this->__likeOr("title", $exps) . " OR\n\t\t\t\t" . $this->__likeOr("content", $exps) . "\n\t\t\t\t) \n\t\t\t\tORDER BY modified DESC"; if ($result = $mediabirdDb->getRecordSet($query, null, 7)) { //reset the topic ids $topicIds = (array) null; //set up array for card ids while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { if ($type & MediabirdSearchType::topic) { $topicId = intval($results['topic']); if (array_search($topicId, $topicIds) === false) { $topicIds[] = $topicId; //collect all topic ids } } if ($type & MediabirdSearchType::card) { $card = (object) null; $card->title = $results['title']; $card->id = intval($results['id']); $cards[] = $card; //collect all card } } } else { error_log($query); return null; } if (count($topicIds) > 0) { //determine data $query = "SELECT id,title,category FROM " . MediabirdConfig::tableName('Topic') . " WHERE id IN (" . join(",", $topicIds) . ")"; if ($result = $mediabirdDb->getRecordSet($query)) { //collect ids while ($results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result))) { $topic = (object) null; $topic->id = intval($results['id']); $topic->group = $this->getPublicTopicGroup($topic->id); $topic->title = $results['title']; $topic->category = $results['category']; $topics[] = $topic; } } else { error_log($query); return null; } } } } //find groups if (count($accessibleGroups) > 0 && $type & MediabirdSearchType::group) { //find groups that have a matching member $select = "group_id IN (" . join(",", $accessibleGroups) . ")\n\t\t\t\t\tAND\n\t\t\t\t\tuser_id IN \n\t\t\t\t\t\t(SELECT id FROM " . MediabirdConfig::tableName('User') . " WHERE \n\t\t\t\t\t\t" . $this->__likeOr("name", $exps) . " OR\n\t\t\t\t\t\t" . $this->__likeOr("email", $exps) . "\n\t\t\t\t\t\t)"; $groupIds = array(); if ($records = $mediabirdDb->getRecords(MediabirdConfig::tableName('Membership', true), $select, 'created DESC', 'group_id', '', 10)) { foreach ($records as $record) { if (in_array($record->group_id, $groupIds) == false) { array_push($groupIds, $record->group_id); } } } //find groups that match description/category/name $select = "id IN (" . join(",", $accessibleGroups) . ") "; if (count($groupIds) > 0) { $select .= "AND\n\t\t\t\tid NOT IN (" . join(",", $groupIds) . ") "; } $select .= "AND\n\t\t\t\t\t(\n\t\t\t\t\t" . $this->__likeOr("name", $exps) . " OR\n\t\t\t\t\t" . $this->__likeOr("description", $exps) . " OR\n\t\t\t\t\t" . $this->__likeOr("category", $exps) . "\n\t\t\t\t\t)"; $records = $mediabirdDb->getRecords(MediabirdConfig::tableName('Group', true), $select, 'created DESC', 'id', '', 7); if ($records) { foreach ($records as $record) { if (in_array($record->id, $groupIds) == false) { array_push($groupIds, $record->id); } } } if (count($groupIds) > 0) { if ($records = $mediabirdDb->getRecords(MediabirdConfig::tableName('Group', true), "id IN (" . join(",", $groupIds) . ")", 'created DESC', "id,name,category,description", '', 15)) { foreach ($records as $record) { $group = (object) null; $group->id = $record->id; $group->title = $record->name; $group->category = $record->category; $group->description = $record->description; $groups[] = $group; } } else { error_log("couldn't find groups"); return null; } } } return array($groups, $topics, $cards); }
/** * Determine changes from a given time for the given user * @param $types string[] * @param $since * @param $userId * @return MediabirdChangeInfo[] */ function getChanges($types,$since=null,$userId=null) { $changes = array(); foreach($types as $type) { if( $type==self::changeTypeCheckConfirmed || $type==self::changeTypeCheckPending) { $itemTypes = array(); //create select clause $select = " modified>'".$this->db->datetime($since)."' AND ( user_id=$userId OR id IN ( SELECT relation_id FROM ".MediabirdConfig::tableName("Relation")." WHERE relation_type='check' AND marker_id IN ( SELECT id FROM ".MediabirdConfig::tableName("Marker")." WHERE (user_id=$userId OR shared=1) AND topic_id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." WHERE user_id=$userId AND mask>=".MediabirdTopicAccessConstants::allowViewingCards." ) ) ) ) "; $sort = 'modified DESC'; //retrieve matching records from db $checkRecords = $this->db->getRecords( MediabirdConfig::tableName('Check',true), $select, $sort ); if($checkRecords) { $checkIds = array(); foreach($checkRecords as $checkRecord) { $checkIds []= intval($checkRecord->id); } if($type==self::changeTypeCheckPending) { //count check states that are pending and related to a check from above $select = "status=0 AND check_id IN (".join(",",$checkIds).")"; $count = $this->db->countRecords(MediabirdConfig::tableName("CheckStatus"),$select); } else if($type==self::changeTypeCheckConfirmed) { //count checks that have been confirmed $select = "status=0 AND check_id IN (".join(",",$checkIds).")"; $checkStatusRecords = $this->db->getRecords(MediabirdConfig::tableName("CheckStatus"),$select); if($checkStatusRecords) { foreach($checkStatusRecords as $checkStatusRecord) { MediabirdUtility::arrayRemove($checkIds,$checkStatusRecord->check_id); } } $count = count($checkIds); } else { continue; } $changeInfo = new MediabirdChangeInfo($this->name,$since,$userId); $changeInfo->changeType = $type; $changeInfo->itemCount = $count; $changes[$type] []= $changeInfo; } } } return $changes; }
/** * Determines new problems that user with user Id can answer to * Returns problem object with: question, answer, questioner, card name, status date, topic name and group name * Sorts results by modification date, descending * @param $userId Id of the user whose notes are to be determined * @param int $fromDate Minimum date from which to return the problems * @param MediabirdDbo $mediabirdDb Database connection to use * @return object */ function findNewProblems($userId,$fromDate,$mediabirdDb) { //determine questions this user can access //and that are of question type 3 $select = "question_mode=3 AND created>'".$mediabirdDb->datetime($fromDate)."' AND (user_id=$this->userId OR id IN ( SELECT relation_id FROM ".MediabirdConfig::tableName("Relation")." WHERE relation_type='question' AND marker_id IN ( SELECT id FROM ".MediabirdConfig::tableName("Marker")." WHERE shared=1 AND card_id IN ( SELECT id FROM ".MediabirdConfig::tableName("Card")." WHERE topic_id IN ( SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." WHERE user_id=$this->userId AND mask>=".MediabirdTopicAccessConstants::allowViewingCards." ) ) ) ))"; $problems = (array)null; $cards = (array)null; if($records = $mediabirdDb->getRecords(MediabirdConfig::tableName('Question',true),$selectProblem,'created DESC','id, question, user_id, modified, created')) { foreach ($records as $result) { //count answers to that question $problem = (object)null; $problem->id = intval($result->id); $problem->created = $problem->date = $mediabirdDb->timestamp($result->created); $problem->modified = $mediabirdDb->timestamp($result->modified); $problem->question = $result->question; $select = "question_id=$result->id"; if($firstAnswerRecords = $mediabirdDb->getRecords(MediabirdConfig::tableName("Answer",true),$select,'created ASC','*', '', 1)) { $problem->answer = $firstAnswerRecords[0]->answer; if($resultQuestioner = $mediabirdDb->getRecord(MediabirdConfig::tableName('User',true),"id=$firstAnswerRecord->user_id")){ $problem->questioner = $resultQuestioner->name; } } /** * formerly given * cardId, cardTitle, topicId, topicTitle, [groupName] */ $problems[] = $problem; } } return $problems; }
if ( isset($environment) ) { $c_send_email = $environment->getConfiguration('c_send_email'); if (isset ($c_send_email)) { if ($c_send_email) { MediabirdConfig :: $disable_mail = false; } else { MediabirdConfig :: $disable_mail = true; } } else { MediabirdConfig :: $disable_mail = false; } } else { MediabirdConfig :: $disable_mail = false; } // proxy: address and port if ( isset($environment) ) { $c_proxy_ip = $environment->getConfiguration('c_proxy_ip'); $c_proxy_port = $environment->getConfiguration('c_proxy_port'); if ( isset($c_proxy_ip) and !empty($c_proxy_ip) ) { MediabirdConfig :: $proxy_address = $c_proxy_ip; if ( isset($c_proxy_port) and !empty($c_proxy_port) ) { MediabirdConfig :: $proxy_port = $c_proxy_port; } } } ?>
$auth = new MediabirdMoodleAuth($mbuser); //set up config MediabirdConfig::$latex_path = $CFG->studynotes_latex_path; MediabirdConfig::$convert_path = $CFG->studynotes_dvipng_path; //set up proxy if (isset($CFG->proxyhost) && strlen($CFG->proxyhost) > 0 && (!isset($CFG->proxytype) || $CFG->proxytype == 'HTTP')) { MediabirdConfig::$proxy_address = $CFG->proxyhost; MediabirdConfig::$proxy_port = $CFG->proxyport; } MediabirdConfig::$uploads_folder = $CFG->dataroot . DIRECTORY_SEPARATOR . "1" . DIRECTORY_SEPARATOR . "moddata" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR; if (!file_exists(MediabirdConfig::$uploads_folder . $auth->userId)) { make_mod_upload_directory(1); make_upload_directory("1/moddata/studynotes/uploads/" . $auth->userId); // we store our images in a subfolder in here } MediabirdConfig::$cache_folder = $CFG->dataroot . DIRECTORY_SEPARATOR . "temp" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR; if (!file_exists(MediabirdConfig::$cache_folder)) { make_upload_directory("temp/studynotes"); } if (isset($action)) { if ($action == "changePass" || $action == "deleteAccount") { exit; } if ($action == "load") { $urlToLoad = MediabirdUtility::getArgNoSlashes($_GET['url']); $html = MediabirdUtility::loadUrl($urlToLoad); if ($html == null) { echo $COULD_NOT_RETRIEVE_LABEL . $urlToLoad; } else { echo $html; }
/** * Send's an anonymous email to some address, preferably the Mediabird team or a user * @param $to Id of user to which to deliver email * @param $subject Subject of email * @param $body Body of email * @return bool Success */ function sendMail($to,$subject,$body) { if(!isset($this->db)) { return false; } if(!MediabirdConfig::$disable_mail) { $address=null; if($to==-1) { $address=MediabirdConfig::$webmaster_address; } else { $query="SELECT email FROM ".MediabirdConfig::tableName('User')." WHERE id=$to"; if($result=$this->db->getRecordSet($query)) { $results=$this->db->recordToArray($this->db->fetchNextRecord($result)); $address=$results['email']; } } if(isset($address)) { $headers = "From: ".MediabirdConfig::$no_reply_address."\r\n". "Reply-To: ".MediabirdConfig::$no_reply_address."\r\n". "X-Mailer: PHP/".phpversion(); return mail($address, $subject, $body, $headers); } } return false; }
/** * Returns quota of current user * * @param int $id Id of user * @param int $default Default value if not given by database * @return int */ static function getUserQuota($id, $default = 0) { global $mediabirdDb; $query = "SELECT quota FROM " . MediabirdConfig::tableName('User') . " WHERE id={$id}"; $result = $mediabirdDb->getRecordSet($query); if ($result && $mediabirdDb->recordLength($result) == 1) { $results = $mediabirdDb->recordToArray($mediabirdDb->fetchNextRecord($result)); $quota = intval($results['quota']); } else { $quota = $default; } return $quota; }
/** * Determines new problems that user with user Id can answer to * Returns problem object with: question, answer, questioner, card name, status date, topic name and group name * Sorts results by modification date, descending * @param $userId Id of the user whose notes are to be determined * @return object */ function findNewProblems($userId, $fromDate) { global $mediabirdDb; $type = "question"; $selectProblem = "notify>0 AND tool='" . $mediabirdDb->escape($type) . "' \n\t\t\t\tAND \n\t\t\t\t\t(modified>'" . $mediabirdDb->datetime($fromDate) . "' OR created>'" . $mediabirdDb->datetime($fromDate) . "')\n\t\t\t\tAND\n\t\t\t\t\t(shared = 1 OR user_id = {$userId})\n\t\t\t\tAND card IN ( \n\t\t\t\t\tSELECT id FROM " . MediabirdConfig::tableName('Card') . " WHERE \n\t\t\t\t\t\ttopic IN (SELECT id FROM " . MediabirdConfig::tableName('Topic') . " WHERE user_id={$userId}) \t\n\t\t\t \tOR topic IN (\n\t\t\t \t\t\tSELECT topic FROM " . MediabirdConfig::tableName('Right') . " WHERE mask>0 AND group_id \n\t\t\t\t \t\t\tIN ( \n\t\t\t\t\t\t\t\t\tSELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$userId} AND active=1)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t)"; $problems = (array) null; $cards = (array) null; if ($results = $mediabirdDb->getRecords(MediabirdConfig::tableName('Marker', true), $selectProblem, 'created DESC', 'id, user_id, card, data, modified, created')) { foreach ($results as $result) { $problem = (object) null; $problem->id = intval($result->id); $result->created = $mediabirdDb->timestamp($result->created); $result->modified = $mediabirdDb->timestamp($result->modified); $problem->date = $result->created; $problem->created = $result->created; $problem->modified = $result->created; $data = json_decode($result->data); if (isset($data->question)) { $problem->question = $data->question; } //check for a suggested answer if (isset($data->answer)) { $problem->answer = $data->answer; } if ($card = $mediabirdDb->getRecord(MediabirdConfig::tableName('Card', true), "id={$result->card}")) { $problem->cardTitle = $card->title; $problem->cardId = $card->id; } $selectTopic = "id = (SELECT topic FROM " . MediabirdConfig::tableName('Card') . " WHERE id={$result->card})"; //check for questioner if ($resultQuestioner = $mediabirdDb->getRecord(MediabirdConfig::tableName('User', true), "id={$result->user_id}")) { $problem->questioner = $resultQuestioner->name; if ($resultTopic = $mediabirdDb->getRecord(MediabirdConfig::tableName('Topic', true), $selectTopic)) { $problem->topicTitle = $resultTopic->title; $problem->topicId = $resultTopic->id; } } $selectGroup = "id IN (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$userId} AND active=1) \n\t\t\t\t\tAND \n\t\t\t\t\t\tid IN (SELECT group_id FROM " . MediabirdConfig::tableName('Membership') . " WHERE user_id={$result->user_id} AND active=1)"; if ($groups = $mediabirdDb->getRecords(MediabirdConfig::tableName('Group', true), $selectGroup, 'id,name')) { if (count($groups) == 1) { $maxGroup = $groups[0]; } else { unset($maximum); foreach ($groups as $group) { if ($rights = $mediabirdDb->getRecords(MediabirdConfig::tableName('Right', true), "topic = {$problem->topicId} AND group_id = {$group->id}")) { foreach ($rights as $right) { if (!isset($maximum) || $right->mask >= $maximum->mask) { $maximum = $right; $maxGroup = $group; } } } } } $problem->groupName = $maxGroup->name; } $problems[] = $problem; } } return $problems; }