function studynotes_handle_session($action, $auth)
{
    global $CFG, $cm;
    require_once $CFG->dirroot . DIRECTORY_SEPARATOR . "mod" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR . "server" . DIRECTORY_SEPARATOR . "data_handling.php";
    require_once $CFG->dirroot . DIRECTORY_SEPARATOR . "mod" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR . "server" . DIRECTORY_SEPARATOR . "filterlib" . DIRECTORY_SEPARATOR . "HTMLPurifier.standalone.php";
    require_once $CFG->dirroot . DIRECTORY_SEPARATOR . "mod" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR . "server" . DIRECTORY_SEPARATOR . "equationsupport" . DIRECTORY_SEPARATOR . "LaTeXrender.php";
    require_once $CFG->dirroot . DIRECTORY_SEPARATOR . "mod" . DIRECTORY_SEPARATOR . "studynotes" . DIRECTORY_SEPARATOR . "server" . DIRECTORY_SEPARATOR . "session_handler.php";
    $data = $action == "upload" ? $_POST : $_POST['data'];
    $ignoreQuotes = true;
    foreach ($_POST['data'] as $key => $value) {
        if (!get_magic_quotes_gpc()) {
            $data[$key] = stripslashes($value);
        }
    }
    if ($action == "upload") {
        $topic = $data['topic'];
        $hasAccess = MediabirdUtility::checkAccess($topic, $auth->userId);
        if ($hasAccess) {
            $userQuota = MediabirdUtility::getUserQuota($auth->userId);
            $quotaLeft = MediabirdUtility::quotaLeft($auth->userId, $userQuota);
            //determine folder path
            $folder = MediabirdConfig::$uploads_folder . $auth->userId . DIRECTORY_SEPARATOR;
            $prefix = MediabirdConfig::$uploads_folder;
            $key = "file";
            $name = $_FILES[$key]['name'];
            $_FILES[$key]['name'] = MediabirdUtility::getFreeFilename($folder);
            $info = MediabirdUtility::storeUpload($key, $folder, $quotaLeft, $prefix);
            if (isset($info['filename']) && strlen($info['filename']) > 0) {
                if ($id = MediabirdUtility::recordFile($info['filename'], 0, $auth->userId, $topic)) {
                    $info['filename'] = 'view.php?action=download&id=' . $cm->id . '&did=' . $id;
                } else {
                    $info['filename'] = null;
                    $info['error'] = "database error";
                }
            } else {
                $info['filename'] = null;
            }
        } else {
            $info['filename'] = null;
            $info['error'] = "invalidtopic";
        }
        echo MediabirdUtility::generateUploadHtml($info['filename'], $info['error']);
        exit;
    }
    if ($action == "download") {
        $id = $_GET['did'];
        if (isset($id)) {
            if ($upload_info = get_record("studynotes_uploads", "id", $id)) {
                $topicId = $upload_info->topic_id;
                $hasAccess = MediabirdUtility::checkAccess($topicId, $auth->userId);
                if ($hasAccess) {
                    MediabirdUtility::readUpload($upload_info->filename, $upload_info->type);
                }
            }
        }
        exit;
    }
    $handler = new MediabirdSessionHandler();
    $reply = $handler->process($action, $auth, $data);
    if (isset($reply->filename) && isset($reply->success) && isset($reply->topic)) {
        if ($id = MediabirdUtility::recordFile($reply->filename, 0, $auth->userId, $reply->topic)) {
            $reply->filename = 'view.php?action=download&id=' . $cm->id . '&did=' . $id;
        } else {
            $reply->success = false;
            $reply->error = "database error";
        }
    }
    header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate;");
    header("Pragma: no-cache;");
    header('Content-Type: application/json;');
    return json_encode($reply);
}
Exemple #2
0
	/**
	 * 
	 */
	function load($data,&$results) {
		if(!isset($data)) {
			$data = array();
		}
		$fromTime = isset($data['topics']['fromTime']) ? $data['topics']['fromTime'] : 0;
		
		$topicLoadedIds = isset($data['topics']['loadedIds']) ? array_values($data['topics']['loadedIds']) : array();
		
		$includeCards = isset($data['topics']['includeCards']) ? $data['topics']['includeCards'] : false;
		
		$ids = isset($data['topics']['restrictIds']) ? array_values($data['topics']['restrictIds']) : array();
			
		//select topics the user can access
		$select = "id IN (
			SELECT topic_id FROM ".MediabirdConfig::tableName("Right")." 
			WHERE 
				user_id=$this->userId AND 
				mask>=".MediabirdTopicAccessConstants::allowViewingCards."
		)";
		
		if(count($ids)>0) {
			$select = "id IN (".join(",",$ids).") AND ".$select; 
		}
		
		$topics = array();
		$referredTagIds = array();
		$checkedPdfs = array();
		
		if($records = $this->db->getRecords(MediabirdConfig::tableName("Topic",true),$select)) {
			foreach($records as $record) {
				$topic = (object)null;
				$topic->id = intval($record->id);
				
				MediabirdUtility::arrayRemove($topicLoadedIds,$topic->id);
				
				$modified = $this->db->timestamp($record->modified);
					
				if($modified > $fromTime) {
					$topic->modified = $modified;
					$topic->title = $record->title;
					$topic->license = intval($record->license);
					$topic->modifier = intval($record->modifier);
				}
				else if(!$includeCards) {
					//ignore rest
					continue;
				}
					
				$select = "topic_id=$record->id";
				
				$cards = array();
				$cardIds = array();
					
				if($cardRecords = $this->db->getRecords(MediabirdConfig::tableName("Card",true),$select,'index_num ASC')) {
					//retrieve cards
					foreach($cardRecords as $cardRecord) {
						$card = (object)null;
						
						$card->id = intval($cardRecord->id);
						
						$cardModified = $this->db->timestamp($cardRecord->modified);
						
						
						if($cardModified > $fromTime) {
							//only collect modified cards for tag retrieval
							$cardIds []= $card->id;
							
							//create empty tags array, will be filled below
							$card->tags = array();
							
							$card->modified = $cardModified;
							$card->title = $cardRecord->title;
							$card->index = intval($cardRecord->index_num);
							$card->modifier = intval($cardRecord->modifier);
							$card->type = intval($cardRecord->content_type);
							if($card->type==MediabirdConstants::cardTypePdf) {
								$card->uploadId = intval($cardRecord->content_id);
								$card->page = intval($cardRecord->content_index);
								
								//only check file auth if it has not been checked for that file
								if(!isset($checkedPdfs[$card->uploadId])) {
									$checkedPdfs[$card->uploadId] = $this->controller->Files->checkFileAuth($card->uploadId);
								}
									
								if(!$checkedPdfs[$card->uploadId]) {
									$card->needsPassword = true;
								}
							}
							
							$cards []= $card;
						}
						else {
   							//return index if topic changed
   							if(property_exists($topic,"modified")) {
   								$card->index = intval($cardRecord->index_num);
   							}
  							
   							$cards []= $card;
						}
					}
					
					//retrieve related CardTags, but only if topic was changed
					if(count($cardIds)>0 && $modified > $fromTime) {
						$select = "card_id IN (".join(",",$cardIds).")";
						
						if($cardTagRecords = $this->db->getRecords(MediabirdConfig::tableName("CardTag",true),$select)) {
							foreach($cardTagRecords as $cardTagRecord) {
								$tagId = intval($cardTagRecord->tag_id);
								
								//save tag id for later retrieval
								if(!in_array($tagId,$referredTagIds)) {
									$referredTagIds []= $tagId;
								}
								
								$cardId = intval($cardTagRecord->card_id);
								
								//attach tags to card objects
								foreach($cards as $card) {
									if($card->id == $cardId) {
										$card->tags []= $tagId;
									}									
								}	
							}
						}
					}
				}

				//save cards in $topic
				$topic->cards = $cards;
				
				//only consider rights if topic has changed
				if($modified > $fromTime) {
				
					//retrieve rights!
					$rights = array();
					if($rightRecords = $this->db->getRecords(MediabirdConfig::tableName('Right',true),"topic_id=$record->id")) {
						foreach($rightRecords as $rightRecord) {
							$right = (object)null;
							$right->id = intval($rightRecord->id);
							
							$right->modified = $this->db->timestamp($rightRecord->modified); 
							
							//this has been commented out since a user that did not know about this topic
							//won't get the complete right set if they have been added later on 
							//if($right->modified > $fromTime) {
							$right->mask = intval($rightRecord->mask);
							$right->userId = intval($rightRecord->user_id);
							$rights []= $right;
							//}
							//else {
							//	//save traffic
							//	unset($right->modified);
							//	$rights []= $right;
							//}
						}
					}
					
					//save rights in $topic
					$topic->rights = $rights;
				}
				
				//add topic if it is to be considered
				$topics []= $topic;
			}
		}
		
		if(count($referredTagIds)>0) {
			$tags = array();
			
			$select = "id IN (".join(",",$referredTagIds).")";
			if($tagRecords = $this->db->getRecords(MediabirdConfig::tableName("Tag",true),$select)) {
				foreach($tagRecords as $tagRecord) {
					$tag = (object)array(
						'id'=>intval($tagRecord->id),
						'color'=>$tagRecord->color,
						'title'=>$tagRecord->title
					);
					$tags []= $tag;
				} 
			}
			
			if(count($tags)>0) {
				$results['tags'] = $tags;
			}
		}
		
		if(count($topics)>0) {
			$results['topics'] = $topics;
		}
		if(count($topicLoadedIds)>0) {
			$results['removedTopicIds'] = $topicLoadedIds;
		}
		return true;
	}
Exemple #3
0
	/**
	 * Loads list of buddies
	 */
	function load($data,&$results) {
		if(!isset($data)) {
			$data = array();
		}
		$fromTime = isset($data['users']['fromTime']) ? $data['users']['fromTime'] : 0;
		$fromTopic = isset($data['users']['fromTopic']) ? $data['users']['fromTopic'] : 0;
		$loadStatesOnly = isset($data['users']['states']) ? $data['users']['states'] : false;

		$loadedIds = isset($data['users']['loadedIds']) ? array_values($data['users']['loadedIds']) : array();
		$avoidIds = isset($data['users']['avoidIds']) ? array_values($data['users']['avoidIds']) : array();
		
		$ids = isset($data['users']['restrictIds']) ? array_values($data['users']['restrictIds']) : array();

		$users = array();

		//if we're loading states, we'll refer to session table which
		//refers to users using user_id rather than id itself
		$className = $loadStatesOnly ? "Session" : "User";
		$userIdColumn = $loadStatesOnly ? "user_id" : "id";

		//select users the current user knows
		$select = "$userIdColumn IN (SELECT user_id FROM ".MediabirdConfig::tableName('Right')." WHERE mask>0 AND";

		//restrict to a given topic if desired
		if($fromTopic>0) {
			$select .= " topic_id=$fromTopic AND";
		}

		//select users from topics the current user has access to
		if($topics = $this->db->getRecords(MediabirdConfig::tableName('Right',true),"user_id=$this->userId AND mask>0",'','topic_id')) {
			$topicIds = array();
			foreach($topics as $topic) {
				if(!in_array($topic->topic_id,$topicIds)) {
					$topicIds []= $topic->topic_id;
				}
			}
			$select .= " topic_id IN (".join(",",$topicIds)."))";
		}
		else {
			//no known users
			return true;
		}

		//only load certain users if desired
		if(count($ids)>0) {
			$select = "$userIdColumn IN (".join(",",$ids).") AND ".$select;
		}
		
		if(count($avoidIds)>0) {
			$select = "$userIdColumn NOT IN (".join(",",$avoidIds).") AND ".$select;
		}
			
		$objects = array();
		if($records = $this->db->getRecords(MediabirdConfig::tableName($className,true),$select)) {
			$time = time();
			foreach($records as $record) {
				$obj = (object)null;
				$obj->id = intval($record->id);
					
				MediabirdUtility::arrayRemove($loadedIds,$obj->id);

				if($loadStatesOnly) {
					//will be saved as int
					$obj->modified = intval($record->modified); 
				}
				else {
					//will be saved as datetime or int
					$obj->modified = $this->db->timestamp($record->modified);
				}
					
				if($obj->modified > $fromTime){
					if($loadStatesOnly) {
						$obj->userId = intval($record->user_id);
						$obj->online = $obj->modified > ($time - $this->sessionTimeout);
						$obj->editing = intval($record->editing);
						$obj->cardId = $obj->online ? intval($record->card_id) : 0;
					}
					else {
						$obj->active = intval($record->active);
						$obj->name = $record->name;
						$obj->email = $record->email;
						$obj->lastLogin = $this->db->timestamp($record->last_login);
						$obj->picUrl = $record->pic_url;
					}
					$objects []= $obj;
				}
			}
		}
			
		if(count($objects)>0) {
			$results[strtolower($className).'s'] = $objects;
		}
		if(count($loadedIds)>0) {
			$results['removed'.$className.'Ids'] = $loadedIds;
		}
		return true;
	}
Exemple #4
0
	function load($data,&$results) {
		if(!isset($data)) {
			$data = array();
		}
		$fromTime = isset($data['questions']['fromTime']) ? $data['questions']['fromTime'] : 0;
		$fromTopic = isset($data['questions']['fromTopic']) ? $data['questions']['fromTopic'] : 0;
			
		$questionLoadedIds = isset($data['questions']['loadedIds']) ? array_values($data['questions']['loadedIds']) : array();
		$answerLoadedIds = isset($data['answers']['loadedIds']) ? array_values($data['answers']['loadedIds']) : array();
		$voteLoadedIds = isset($data['votes']['loadedIds']) ? array_values($data['votes']['loadedIds']) : array();
		$starLoadedIds = isset($data['stars']['loadedIds']) ? array_values($data['stars']['loadedIds']) : array();
			
		$ids = isset($data['questions']['restrictIds']) ? array_values($data['questions']['restrictIds']) : array();
			
		if($fromTopic == 0) {
			$select = "(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 (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."
					)
				)
			))";
			
			if(count($ids)>0) {
				$select = "id IN (".join(",",$ids).") AND ".$select;
			}
		}
		else {
			$select = "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=$this->userId OR shared=1) AND topic_id=$fromTopic
				)
			)";	
		}
			
		$questions = array();
			
		if($records = $this->db->getRecords(MediabirdConfig::tableName("Question",true),$select)) {
			foreach($records as $record) {
				$hasChanges = false; //defines if this question should be returned or not
				
				$question = (object)null;
				$question->id = intval($record->id);
				
				MediabirdUtility::arrayRemove($questionLoadedIds,$question->id);
				
				$question->modified = $this->db->timestamp($record->modified);
					
				//this more complicated approach is required,
				//because question records won't be updated even
				//if answers, votes or stars change!
				//as a result, we have to go through all related records
				//even if the question is up to date!
				if($question->modified > $fromTime) {
					//send question and modification date back if newer than fromTime
					$question->question = $record->question;
					$question->mode = intval($record->question_mode);
					$question->userId = intval($record->user_id);
					$question->modifier = intval($record->modifier);
					
					//in case database was upgraded, it won't feature a valid modifier entry
					if($question->modifier==0) {
						$question->modifier = $question->userId;
					}
					
					$hasChanges = true;
				}
					
				//load answers
				$select = "question_id=$question->id";
				if($answerRecords = $this->db->getRecords(MediabirdConfig::tableName("Answer",true),$select)) {
					$question->answers = array();
					$question->votes = array();
					foreach($answerRecords as $answerRecord) {
						$answer = (object) array(
								'id'=>intval($answerRecord->id),
								'answer'=>$answerRecord->answer,
								'userId'=>intval($answerRecord->user_id),
								'modified'=>$this->db->timestamp($answerRecord->modified)
						);
							
						MediabirdUtility::arrayRemove($answerLoadedIds,$answer->id);
							
						if($answer->modified > $fromTime) {
							$question->answers []= $answer;
							$hasChanges = true;
						}
							
						//load votes
						$select = "answer_id=$answerRecord->id";
						if($voteRecords = $this->db->getRecords(MediabirdConfig::tableName("Vote",true),$select)) {
							foreach($voteRecords as $voteRecord) {
								$vote = (object)array(
									'id'=>intval($voteRecord->id),
									'modified'=>$this->db->timestamp($voteRecord->modified),
									'userId'=>intval($voteRecord->user_id),
									'answerId'=>intval($voteRecord->answer_id)
								);
								MediabirdUtility::arrayRemove($voteLoadedIds,$vote->id);
									
								if($vote->modified > $fromTime) {
									$question->votes []= $vote;
									$hasChanges = true;
								}
							}
						}
					}
				}
					
				//load star for current user
				$select = "question_id=$question->id AND user_id=$this->userId";
				if($starRecord = $this->db->getRecord(MediabirdConfig::tableName("Star",true),$select)) {
					$star = (object) array(
							'id'=>intval($starRecord->id),
							'userId'=>intval($starRecord->user_id),
							'answerId'=>intval($starRecord->answer_id),
							'modified'=>$this->db->timestamp($starRecord->modified)
					);

					MediabirdUtility::arrayRemove($starLoadedIds,$star->id);

					if($star->modified > $fromTime) {
						$question->stars = array($star);
						$hasChanges = true;
					}
				}
				
				if($hasChanges) {
					$questions []= $question;
				}
			}
		}
			
		if(count($questions)>0) {
			$results['questions'] = $questions;
		}
		if(count($questionLoadedIds)>0) {
			$results['removedQuestionIds'] = $questionLoadedIds;
		}
		if(count($voteLoadedIds)>0) {
			$results['removedVoteIds'] = $voteLoadedIds;
		}
		if(count($starLoadedIds)>0) {
			$results['removedStarIds'] = $starLoadedIds;
		}
		if(count($answerLoadedIds)>0) {
			$results['removedAnswerIds'] = $answerLoadedIds;
		}
		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='" . $mediabirdDb->escape($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;
 }
Exemple #6
0
	/**
	 * 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;
		}
	}
Exemple #7
0
include ($plugin_dir.'/config/config.php');

//include commsy auth interface
include ($plugin_dir.'/commsy_auth.php');
$auth = new CommsyAuthManager($environment);

include_once($plugin_dir.'/server/db_mysql.php');
$mediabirdDb = new MediabirdDboMySql();

//set database interface 
$auth->setDb($mediabirdDb);

if($mediabirdDb->connect()) {
		
		$controller = new MediabirdController($mediabirdDb,$auth);
		$reply = $controller->dispatch($action, $_POST);
		
		$mediabirdDb->disconnect();
		
		MediabirdUtility::jsonHeader();
		if(!empty($reply)) {
			echo json_encode($reply);
		}
}
else {
	exit;
}
flush();
exit();
?>
	function perform($config_path) {
	/*
	todo:
	* check ghostscript capabilities of convert
	* render formula for test purpose
	* check pages of given pdf file
	*/
		
		$result = true;
?>
<table>
	<tr>
		<th>Check</th>
		<th>Status</th>
		<th>Hint</th>
	</tr>
	<tr>
		<?php
		$result = $result && file_exists($config_path);
		?>
		<td>Configuration present</td>
		<td class="<?php echo $result ? 'green' : 'red'; ?>"><?php echo $result ? "Yes":"No"; ?></td>
		<td>
		<?php if(!$result): ?>
		Run <a href="../setup/index.php">setup</a> first.
		<?php endif; ?>
		</td>
	</tr>
	<?php if ($result): ?>
	<tr>
		<?php
		include_once($config_path);
		$result = (!empty(MediabirdConfig::$pdftk_path) && MediabirdUtility::execExists(MediabirdConfig::$pdftk_path)) || (!empty(MediabirdConfig::$pdfinfo_path) && MediabirdUtility::execExists(MediabirdConfig::$pdfinfo_path));
		?>
		<td>PdfTk or pdfinfo accessible</td>
		<td class="<?php echo $result ? 'green' : 'red'; ?>"><?php echo $result ? "Yes":"No"; ?></td>
		<td>
		<?php if(!$result): ?>
		Install pdftk or pdfinfo. You might have to specify the path to pdftk or pdfinfo in the module options or config file.
		<?php endif; ?>
		</td>
	</tr>
	<tr>
		<?php
		$result = MediabirdUtility::execExists(MediabirdConfig::$latex_path);
		?>
		<td>LaTeX accessible</td>
		<td class="<?php echo $result ? 'green' : 'red'; ?>"><?php echo $result ? "Yes":"No"; ?></td>
		<td>
		<?php if(!$result): ?>
		Install LaTeX and specify the path to the latex executable in the module options or config file.
		<?php endif; ?>
		</td>
	</tr>
	<tr>
		<?php
		$result = MediabirdUtility::execExists(MediabirdConfig::$convert_path);
		?>
		<td>LaTeX helper DVIPNG accessible</td>
		<td class="<?php echo $result ? 'green' : 'red'; ?>"><?php echo $result ? "Yes":"No"; ?></td>
		<td>
		<?php if(!$result): ?>
		Install dvipng and specify the path to the dvipng executable in the module options or config file.
		<?php endif; ?>
		</td>
	</tr>
	<tr>
		<?php
		$result = MediabirdUtility::execExists(MediabirdConfig::$magic_path);
		?>
		<td>ImageMagick accessible</td>
		<td class="<?php echo $result ? 'green' : 'red'; ?>"><?php echo $result ? "Yes":"No"; ?></td>
		<td>
		<?php if(!$result): ?>
		Install ImageMagick and specify the path to the convert executable in the module options or config file.
		<?php endif; ?>
		</td>
	</tr>
	<?php endif; ?>
</table><?php
	}	
Exemple #9
0
	function feedback($args) {
		if(!MediabirdUtility::checkKeyset($args,array('desc'))) {
			return false;
		}
		
		$description = $args->desc;

		$results = array();
		
		$body = "User with id $this->userId has suggested the following feature:\n".$description;
		$body = wordwrap($body, 70);

		if (!MediabirdConfig::$disable_mail) {
			$oldReporting = error_reporting(0);
			if (method_exists($this->auth, 'sendMail') && $this->auth->sendMail(-1, "Mediabird Feedback", $body)) {
				$result = MediabirdConstants::processed;
			}
			else {
				$result = MediabirdConstants::serverError;
			}
			error_reporting($oldReporting);
		}
		else {
			error_log("Feature suggested by user $this->userId: $description .");
			$result = MediabirdConstants::processed;
		}
		
		$results['r'] = $result;
		
		return $results;
	}
Exemple #10
0
	function validateCopy($data,&$cache,&$reason) {

		//incoming: array of ids to be deep-copied
		$validates = is_object($data) && MediabirdUtility::checkKeyset($data,$this->copyParams);

		if($validates && (!is_array($data->ids) || count($data->ids)==0)) {
			$validates = false;
		}
			
		if($validates) {
			foreach($data->ids as $id) {
				if(!is_int($id)) {
					$validates = false;
					break;
				}
			}
		}

		if($validates) {
			//select files that the current user was granted access to (protected files)
			$select .= "id IN (
				SELECT upload_id FROM ".MediabirdConfig::tableName("UploadAccess")." WHERE user_id=$this->userId AND mask>0 
			)";

			//select files of users the current user knows
			$select .= " OR id IN (
				SELECT content_id FROM ".MediabirdConfig::tableName("Card")." WHERE content_type=".MediabirdConstants::cardTypePdf." AND topic_id IN (
					SELECT topic_id FROM ".MediabirdConfig::tableName('Right')." WHERE user_id=$this->userId AND mask>0
				)
			)";

			//select files not owned by current user (slicing)
			$select = "user_id != $this->userId AND (".$select.")";

			//slice by given ids
			$select = "id IN (".join(",",$data->ids).") AND (".$select.")";

			$records = $this->db->getRecords(MediabirdConfig::tableName("Upload",true),$select);

			if(!$records || count($records) != count($data->ids)) {
				$validates = false;
			}
		}
			
		if($validates) {
			$cache['uploadRecords'] = isset($records) ? $records : array();
		}
			
		if(!$validates && !isset($reason)) {
			$reason = MediabirdConstants::invalidData;
		}
			
		return $validates;
	}
Exemple #11
0
	function load($data,&$results) {
		if(!isset($data)) {
			$data = array();
		}
		$fromTime = isset($data['links']['fromTime']) ? $data['links']['fromTime'] : 0;
		$loadedIds = isset($data['links']['loadedIds']) ? array_values($data['links']['loadedIds']) : array();
			
		$ids = isset($data['links']['restrictIds']) ? array_values($data['links']['restrictIds']) : array();
			
		$links = array();
			
		$select = "(user_id=$this->userId OR id IN (
				SELECT relation_id FROM ".MediabirdConfig::tableName("Relation")." WHERE relation_type='link' AND marker_id IN (
					SELECT id FROM ".MediabirdConfig::tableName("Marker")." WHERE (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."
					)
				)
			))";
			
		if(count($ids)>0) {
			$select = "id IN (".join(",",$ids).") AND ".$select;
		}
			
		$links = array();
			
		if($records = $this->db->getRecords(MediabirdConfig::tableName("Link",true),$select)) {
			foreach($records as $record) {
				$link = (object)null;
				$link->id = intval($record->id);
					
				MediabirdUtility::arrayRemove($loadedIds,$link->id);
					
				$link->modified = $this->db->timestamp($record->modified);
					
				if($link->modified > $fromTime){
					$link->title = $record->title;
					$link->url = $record->url;
					$link->type = intval($record->type_num);
					$link->userId = intval($record->user_id);
					$link->modifier = intval($record->modifier);
					
					//in case database was upgraded, it won't feature a valid modifier entry
					if($link->modifier==0) {
						$link->modifier = $link->userId;
					}
					
					$links []= $link;
				}
			}
		}
			
			
		$results['links'] = $links;
		if(count($loadedIds)>0) {
			$results['removedLinkIds'] = $loadedIds;
		}
		return true;
	}
Exemple #12
0
	function load($data,&$results) {
		if(!isset($data)) {
			$data = array();
		}
		$fromTime = isset($data['flashcards']['fromTime']) ? $data['flashcards']['fromTime'] : 0;
		$loadedIds = isset($data['flashcards']['loadedIds']) ? array_values($data['flashcards']['loadedIds']) : array();
			
		$ids = isset($data['flashcards']['restrictIds']) ? array_values($data['flashcards']['restrictIds']) : array();
			
		$flashcards = array();
			
		$select = "user_id=$this->userId";
			
		if(count($ids)>0) {
			$select = "id IN (".join(",",$ids).") AND ".$select;
		}
			
		$flashcards = array();
			
		if($records = $this->db->getRecords(MediabirdConfig::tableName("Flashcard",true),$select)) {
			foreach($records as $record) {
				$flashcard = (object)null;
				$flashcard->id = intval($record->id);
					
				MediabirdUtility::arrayRemove($loadedIds,$flashcard->id);
					
				$modified = $this->db->timestamp($record->modified);
					
				if($modified>$fromTime){
					$flashcard->level = intval($record->level_num);
					$flashcard->answerTime = intval($record->answer_time);
					$flashcard->results = $this->resultsFromTraining($record->results);

					$flashcards []= $flashcard;
				}
			}
		}
			
		if(count($flashcards)>0) {
			$results['flashcards'] = $flashcards;
		}
		if(count($loadedIds)>0) {
			$results['removedFlashcardIds'] = $loadedIds;
		}
		return true;
	}
Exemple #13
0
	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;
	}
Exemple #14
0
	function validate($data,&$cache,&$reason) {
		$validates = is_object($data) && MediabirdUtility::checkKeyset($data,$this->updateParams) && is_array($data->tagColors) && count($data->tagColors)>0;
		
		$referredTagIds = array();
		
		if($validates) {
			foreach($data->tagColors as $tagColor) {
				//check if only valid keys are given
				if(!MediabirdUtility::checkKeyset($tagColor,$this->tagProperties,true)) {
					$validates = false;
					break;
				}
				
				//check if id and at least color or showText are given
				if(!property_exists($tagColor,'tagId') || (!property_exists($tagColor,'color') && !property_exists($tagColor,'showText'))) {
					$validates = false;
					break;
				}
				
				//tag id must be given as int
				if(!is_int($tagColor->tagId)) {
					$validates = false;
					break;
				}
				
				if(!in_array($tagColor->tagId,$referredTagIds,true)) {
					$referredTagIds []= $tagColor->tagId;
				}
				else {
					//tagId should not be given twice
					$validates = false;
					break;
				}
				
				//validate color
				if(property_exists($tagColor,'color') && !$this->validateHexColor($tagColor->color)) {
					$validates = false;
					break;
				}
				
				//validate showText
				if(property_exists($tagColor,'showText') && !in_array($tagColor->showText,$this->allowedShowStates,true)) {
					$validates = false;
					break;
				}
			}
			
			if($validates) {
				$select = "id IN (".join(",",$referredTagIds).")";
				if($this->db->countRecords(MediabirdConfig::tableName("Tag",true),$select)!=count($referredTagIds)) {
					$validates = false;
				}
				else {
					$cache ['referredTagIds'] = $referredTagIds;
				}
			}
		}
		
		if(!$validates && !isset($reason)) {
			$reason = MediabirdConstants::invalidData;
		}
			
		return $validates;
	}
 /**
  * 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='" . $mediabirdDb->escape($current) . "'";
             $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='" . $mediabirdDb->escape($current) . "'");
                 //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;
 }
Exemple #16
0
	/**
	 * 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;
	}
 /**
  * Retrieves a remote url using CURL making absolute links relative
  * @param string $urlToLoad
  * @return string HTML
  */
 static function loadUrl($urlToLoad)
 {
     // create a new cURL resource
     $ch = curl_init();
     // set URL and other appropriate options
     curl_setopt($ch, CURLOPT_URL, $urlToLoad);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     //set up proxy if specified
     if (isset(MediabirdConfig::$proxy_address) && strlen(MediabirdConfig::$proxy_address) > 0) {
         curl_setopt($ch, CURLOPT_PROXY, MediabirdConfig::$proxy_address . ":" . MediabirdConfig::$proxy_port);
     }
     //execute
     $html = curl_exec($ch);
     //check for error
     if ($html === false) {
         return null;
     }
     // grab URL and pass it to the browser
     $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
     // grab content type and pass it to the browser
     $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
     if (isset($type)) {
         header('Content-Type: ' . $type);
     }
     //parse the url
     $path = parse_url($finalUrl);
     //remove last bit of path
     if (isset($path['path'])) {
         $li = strrpos($path['path'], "/");
         if ($li > -1) {
             $path['path'] = substr($path['path'], 0, $li + 1);
         }
     }
     //forget about query and fragment
     unset($path['query']);
     unset($path['fragment']);
     //construct base url
     self::$baseUrl = self::__glueUrl($path);
     //construct the root url
     unset($path['path']);
     self::$rootUrl = self::__glueUrl($path);
     //correct relative URIs
     $html = self::makeLinksAbsolute($html);
     // close cURL resource, and free up system resources
     curl_close($ch);
     //echo modified HTML
     return $html;
 }
Exemple #18
0
	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;
	}