diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0008b19 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# 設定檔 +htdocs/config.php + +# 建立測試用的檔案 +test.php +htdocs/tests/ + +# KDE Dolphin自己產生的垃圾 +*.directory +.*.kate-swp +.DS_Store +.*.swp + + +# GitEye產生的 +.project + +# phpdoc產生的檔案 +docs/ +docs/phpdoc-cache-* + +# PHP Composer +composer.phar +vendor/ + +# Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +composer.lock + +# Gem +Gemfile.lock diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..2ec68f2 --- /dev/null +++ b/Gemfile @@ -0,0 +1,11 @@ +source 'https://rubygems.org' +group :development do + gem 'guard' + gem 'guard-livereload', require: false + gem 'guard-shell' + gem 'guard-phpunit2' + gem 'rb-fsevent' + gem 'ruby_gntp' + gem 'growl' + gem 'libnotify' +end \ No newline at end of file diff --git a/Guardfile b/Guardfile index e773bcb..bd862b6 100644 --- a/Guardfile +++ b/Guardfile @@ -1,18 +1,32 @@ # A sample Guardfile # More info at https://github.com/guard/guard#readme -group :development do - gem 'guard-livereload', require: false -end - # Add files and commands to this file, like the example: # watch(%r{file/path}) { `command(s)` } # + +# Mac用的通知中心 +notification :growl +# Linux用的通知中心 +notification :libnotify + +#PHPDoc guard :shell do - watch(%r{htdocs/.+\.(php)}) { 'phpdoc -d ./htdocs/lib -t ./docs/' } + watch(%r{htdocs/.+\.(php)}) do + system 'phpdoc', '-d', './htdocs/lib', '-t', './docs/' + end end # LiveReload guard 'livereload' do watch(%r{htdocs/.+\.(php|css|js|html)}) end + +# PHPUnit +guard :phpunit2, :all_on_start => false, :tests_path => 'tests/', :cli => '--colors -c phpunit.xml' do + # Run any test in app/tests upon save. + watch(%r{^tests/.+Test\.php$}) + + # When a file is edited, try to run its associated test. + watch(%r{^htdocs/lib/(.+)\.php}) { |m| "tests/#{m[1]}Test.php" } +end \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c696e26 --- /dev/null +++ b/README.md @@ -0,0 +1,176 @@ +後端伺服器 +=== +主要的東西都放在Server那邊,處理手機客戶端與伺服器資料的溝通。 + +包含每位學生的學習資料、場地狀況、學習教材。以及處理學習路徑規劃。 + +## 使用需求 + +* PHP5.3 以上,需要有以下Extension: + * pdo-mysql + * zip + * mcrypt +* MariaDB 5.5.31 (可用MySQL) + +## 建置伺服器環境 + +### 1. 安裝Apache + MySQL + +For Linux Debian, Ubuntu: + + # 更新套件庫、升級系統內套件 + sudo apt-get update; sudo apt-get upgrade -y + # 安裝Apache, MySQL, PHP(附帶需要的Extensions) + sudo apt-get install apache2 mysql-server php5 php5-mysql php5-mcrypt phpmyadmin -y + +### 2. 編輯Apache網站設定檔(vhost) + +1. 編輯以下文件: + * ArchLinux: `/etc/httpd/conf/extra/httpd-vhosts.conf` + * Ubuntu: `/etc/apache2/sites-available/uelearning.conf` + + 加入以下內容: + + + ServerName uelearning.yourdomain.name + ServerAdmin admin@yourdomain.name + + DocumentRoot /srv/http/website/E-learning-Server/htdocs + DirectoryIndex index.php index.shtml index.html + + + Options FollowSymLinks MultiViews + AllowOverride All + Allow from All + Order allow,deny + Require all granted #Apache 2.4以上版本需加此行,若在Apache2.2請移除此行 + + +2. 啟用本站/重新啟動伺服器: + * ArchLinux: `$ sudo systemctl restart httpd.service` + * Debian, Ubuntu: + 1. `$ sudo a2ensite uelearning` + 2. `$ service apache2 reload` + +### 3. 編輯Apache設定 +Linux Debian: `sudo a2enmod rewrite` + +非Debian or Ubuntu的,請開啟以下設定檔: + +* Windows: 到`C:\AppServ\Apache2.2\conf\httpd.conf` +* Arch Linux: 到`/etc/httpd/conf/httpd.conf` + +將 `LoadModule rewrite_module modules/mod_rewrite.so` 取消註解 + +### 4. 編輯PHP設定 + +開啟以下設定檔: + +* Windows: 到`C:\Windows\php.ini +* Arch Linux: 到`/etc/php/php.ini` + +找到`output_buffering`那行修改成 `output_buffering = On`。(`output_buffering = 4096`也OK) + +並將`extension=php_pdo.dll`和`extension=php_pdo_mysql.dll`取消註解。(Linux請把`.so`當成`.dll`看待) + +### 5. 啟用本站/重新啟動伺服器: + +* Windows: + 1. `C:\AppServ\Apache2.2\apache_serviceuninstall.bat` + 2. `C:\AppServ\Apache2.2\apache_serviceinstall.bat` +* ArchLinux: `$ sudo systemctl restart httpd.service` +* Ubuntu: `$ sudo service apache2 reload` + +## 安裝此系統 +請擇一選擇安裝方式: +### 引導式安裝 +**>>> 施工中,請勿使用 <<<** + +### 手動安裝 +1. 請先把 `/htdocs/` 整個複製到你的網頁空間 +2. 將內附的 `/sql/UElearning.sql` 匯入進你的資料庫 +3. 將 `/htdocs/config.sample.php` 檔案複製成 `config.php` ,並依你的需求修改。 + + +*** + +## 開發需求 +* 支援UTF-8編碼的文字編輯器 +* 開發文件產生器: phpdoc +* 單元測試: phpunit +* 自動化建置工具 + * guard(需有ruby環境) + * guard-shell + * guard-livereload + * guard-phpunit2 (不是guard-phpunit) + +## 建置開發環境 +### 安裝PHP套件管理程式-pear + sudo apt-get install php-pear + +### 安裝PHPDoc, PHPUnit +安裝PHPDoc: + + sudo pear channel-discover pear.phpdoc.org + sudo pear install phpdoc/phpDocumentor + +安裝PHPUnit: + + sudo pear channel-discover pear.phpunit.de + sudo pear install phpunit/PHPUnit + +### 安裝自動化工具 +安裝Guard所需套件 + + sudo apt-get install g++ gem wget + sudo gem install bundler + +安裝此專案所需的套件 + + cd E-learning-Server # 進入專案資料夾 + bundler install + bundle exec guard + +PS. 若出現`ArgumentError: invalid byte sequence in US-ASCII`錯誤,是因為Ruby<2.0 以下版本預設編碼是採用**US-ASCII**,必須下以下兩行指令來修正此問題: + + export LANG="C.UTF-8" + export LC_ALL="C.UTF-8" + +為了減少每次都要下此兩行的麻煩,建議可寫在`~/.bashrc`裡,自動指定編碼。 + +### 瀏覽器plugin安裝 +[LiveReload - browser extensions](http://feedback.livereload.com/knowledgebase/articles/86242-how-do-i-install-and-use-the-browser-extensions-) + +支援主流瀏覽器: Firefox, Chrome, Safari + +## 自動化建置 (開發前建議啟動) +撰寫程式前,可在專案內下以下指令即可啟動 + + guard + +啟動後會監視專案內的`.php`檔案,一有任何變動將會 + +* phpdoc: 重新建立開發文件 +* livereload: 呼叫瀏覽器自動重新整理 +* phpunit2: 單元測試是否可成功執行 + +#### 相關參考 +* +* + +## 開發文件 +已將整份專案使用[PHPDocumentor](http://www.phpdoc.org/)產生出[開發文件網站](docs/index.html) + +PS. 若有使用Guard的話可不需手動下此指令,會自動連同一起產生 + +產生指令: + + phpdoc -d ./htdocs/lib -t ./docs/ + +## 單元測試 +PS. 若有使用Guard的話,會自動對你正在編輯的檔案進行測試 + +測試指令: + + cd test # 進入測試資料夾 + phpunit --bootstrap ../htdocs/config.php <要測試的檔案> \ No newline at end of file diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 0000000..dd3e602 --- /dev/null +++ b/cli/README.md @@ -0,0 +1,4 @@ +後端伺服器 (指令界面) +=== + +這個... 現在沒有東西,就這樣 (逃 diff --git a/cli/composer.json b/cli/composer.json new file mode 100644 index 0000000..22c007b --- /dev/null +++ b/cli/composer.json @@ -0,0 +1,7 @@ +{ + "name": "uelearning", + "description": "UElearning", + "require": { + "symfony/console": "2.5.*" + } +} diff --git a/cli/here b/cli/here new file mode 100644 index 0000000..e69de29 diff --git a/cli/uelearning.php b/cli/uelearning.php new file mode 100644 index 0000000..aefbddd --- /dev/null +++ b/cli/uelearning.php @@ -0,0 +1,18 @@ +#!/usr/bin/env php +run(); +?> \ No newline at end of file diff --git a/htdocs/API/v2/here b/htdocs/API/v2/here new file mode 100644 index 0000000..e69de29 diff --git a/htdocs/assets/here b/htdocs/assets/here new file mode 100644 index 0000000..e69de29 diff --git a/htdocs/composer.json b/htdocs/composer.json new file mode 100644 index 0000000..0c5c5d1 --- /dev/null +++ b/htdocs/composer.json @@ -0,0 +1,10 @@ +{ + "name": "chu-tdap/uelearning", + "description": "無所不在學習導引系統之研製", + "authors": [ + { + "name": "Yuan Chiu", + "email": "chyuaner@gmail.com" + } + } +} diff --git a/htdocs/config.sample.php b/htdocs/config.sample.php new file mode 100644 index 0000000..871814d --- /dev/null +++ b/htdocs/config.sample.php @@ -0,0 +1,111 @@ + + *
  • MD5
  • + *
  • SHA1
  • + *
  • CRYPT
  • + * + */ + define('ENCRYPT_MODE', 'SHA1'); + + /** + * 你的地區 + */ + date_default_timezone_set('Asia/Taipei'); //設定時區 + +// 路徑設定 =================================================================== + /** + * 網站根目錄 + */ + define('UELEARNING_ROOT', __DIR__); + + /** + * 內部函式庫根目錄 + */ + define('UELEARNING_LIB_ROOT', __DIR__.'/lib'); + + /** + * 這份設定檔的路徑 + */ + define('UELEARNING_CONFIG_PATH', __FILE__); diff --git a/htdocs/debug/project_info.php b/htdocs/debug/project_info.php new file mode 100644 index 0000000..3f66fbf --- /dev/null +++ b/htdocs/debug/project_info.php @@ -0,0 +1,27 @@ + + + + + + + 專案設定資訊 + + +

    系統資訊

    + + +

    專案設定資訊

    + + + \ No newline at end of file diff --git a/htdocs/index.php b/htdocs/index.php new file mode 100644 index 0000000..b39c40d --- /dev/null +++ b/htdocs/index.php @@ -0,0 +1,11 @@ + + + + + Creating... + + +

    建置中~

    + + + \ No newline at end of file diff --git a/htdocs/lib/Config/Exception.php b/htdocs/lib/Config/Exception.php new file mode 100644 index 0000000..da28aee --- /dev/null +++ b/htdocs/lib/Config/Exception.php @@ -0,0 +1,10 @@ + 'mysql', + * 'host' => 'localhost', + * 'port' => '3306', + * 'user' => 'user', + * 'password' => '123456', + * 'dbname' => 'chu-elearning', + * 'prefix' => 'chu_' + * )); + * + * 可參考以下範例: + * + * require_once __DIR__.'/config.php'; + * require_once UELEARNING_LIB_ROOT.'Database/DBAdmin.php'; + * use UElearning\Database; + * + * try { + * $db = new Database\DBAdmin(); + * } catch (Database\Exception\DatabaseNoSupportException $e) { + * echo 'No Support in ', $e->getType(); + * } catch (Exception $e) { + * echo 'Caught other exception: ', $e->getMessage(); + * } + * + * @author Yuan Chiu + * @version 2.0.0 + * @package UElearning + * @subpackage Database + */ +class DBAdmin extends Database { + + /** + * 建立所有所需的資料表 + * + * @since 2.0.0 + */ + public function createAllTable() { + + // 使用的資料庫系統為MySQL + if($this->db_type == 'mysql') { + + // 所有要跑的SQL指令陣列 + $execSql = array( + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."ABelong` ( + `TID` int(10) unsigned NOT NULL, + `AID` int(10) unsigned NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."AGroup` ( + `GID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `GName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `GMemo` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`GID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Area` ( + `AID` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '區域編號', + `AName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '區域名稱', + `AMapID` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '區域地圖編號', + `AIntroduction` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`AID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."CGroup` ( + `CID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `CName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `CMemo` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`CID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Edge` ( + `Ti` int(11) NOT NULL, + `Tj` int(11) NOT NULL, + `MoveTime` int(4) NOT NULL COMMENT '移動時間(分鐘)', + `Destance` int(11) NOT NULL COMMENT '距離(M)' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."LearnActivity` ( + `LsID` int(10) NOT NULL, + `ThID` int(10) NOT NULL COMMENT '主題編號', + `CID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '班級名稱', + `StartTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '開始時間', + `Delay` int(11) NOT NULL COMMENT '實際狀態延誤(分)', + PRIMARY KEY (`LsID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Material` ( + `MID` int(10) unsigned NOT NULL COMMENT '教材內部編號', + `TID` int(10) unsigned NOT NULL COMMENT '標的內部編號', + `MMode` int(1) NOT NULL DEFAULT '0' COMMENT '教材模式', + `MUrl` varchar(1000) COLLATE utf8_unicode_ci NOT NULL COMMENT '教材檔案路徑', + PRIMARY KEY (`MID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Recommand` ( + `TID` int(3) NOT NULL COMMENT '標的內部編號', + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者帳號', + `gradation` int(11) NOT NULL COMMENT '系統推薦標地順序' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Study` ( + `SID` int(10) NOT NULL AUTO_INCREMENT, + `TID` int(10) NOT NULL COMMENT '標的內部編號', + `UID` int(30) NOT NULL COMMENT '使用者名稱', + `LMode` int(11) NOT NULL COMMENT '學習導引模式', + `MMode` int(11) NOT NULL COMMENT '教材模式', + `In_TargetTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '進入標的時間', + `Out_TargetTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '離開標的時間', + PRIMARY KEY (`SID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."StudyQuestion` ( + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `TID` int(10) NOT NULL, + `QID` int(11) NOT NULL, + `UAns` int(11) NOT NULL, + `CAns` int(11) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Target` ( + `TID` int(10) unsigned NOT NULL COMMENT '標的內部編號', + `TNum` int(10) DEFAULT NULL COMMENT '標的地圖上的編號', + `TName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '標的名稱', + `TMapID` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地圖圖檔名稱', + `TLearnTime` int(4) unsigned NOT NULL COMMENT '預估此標的應該學習的時間', + `PLj` int(11) unsigned NOT NULL COMMENT '學習標的的人數限制', + `Mj` int(11) unsigned DEFAULT NULL COMMENT '目前人數', + `S` int(11) unsigned DEFAULT NULL COMMENT '學習標的飽和率上限', + `Fi` int(11) DEFAULT NULL COMMENT '學習標的滿額指標', + PRIMARY KEY (`TID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."TBelong` ( + `TID` int(10) NOT NULL, + `ThID` int(10) NOT NULL, + `Weights` int(3) NOT NULL COMMENT '當次學習主題的某一個學習標的之權重' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."Theme` ( + `ThID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ThName` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT '主題名稱', + `ThLearnTotal` int(4) NOT NULL COMMENT '學習此主題要花的總時間(m)', + `ThIntroduction` tinytext COLLATE utf8_unicode_ci COMMENT '介紹', + PRIMARY KEY (`ThID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."User` ( + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者帳號', + `UPassword` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT '密碼', + `GID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者群組', + `CID` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用者班級', + `UEnabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '帳號啟用狀態', + `UBuild_Time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '帳號建立時間', + `LMode` enum('line-learn','harf-line-learn','non-line-learn') COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '學習導引模式', + `MMode` int(11) DEFAULT NULL COMMENT '教材模式', + `UNickname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '暱稱', + `UReal_Name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '真實姓名', + `UEmail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用者email', + `UMemo` tinytext COLLATE utf8_unicode_ci COMMENT '備註', + PRIMARY KEY (`UID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", + +"CREATE TABLE IF NOT EXISTS `".$this->db_prefix."UserSession` ( + `UsID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `UToken` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '此登入階段的token', + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `UAgent` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用哪個裝置登入', + `ULoginDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '登入時間', + `ULogoutDate` timestamp NULL DEFAULT NULL COMMENT '登出時間', + PRIMARY KEY (`UsID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;" + ); + + // 執行此SQL指令 + foreach ($execSql as $value ){ + $this->connDB->exec($value); + }; + } + else { + throw new Exception\DatabaseNoSupportException($this->db_type); + } + } +} \ No newline at end of file diff --git a/htdocs/lib/Database/DBUser.php b/htdocs/lib/Database/DBUser.php new file mode 100644 index 0000000..f5d9aa9 --- /dev/null +++ b/htdocs/lib/Database/DBUser.php @@ -0,0 +1,670 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage Database + */ +class DBUser extends Database { + + const FORM_USER = 'User'; + + /** + * 新增一個使用者 + * + * 範例: + * + * require_once __DIR__.'/../config.php'; + * require_once UELEARNING_LIB_ROOT.'/Database/DBUser.php'; + * use UElearning\Database; + * + * try { + * $db = new Database\DBUser(); + * + * $db->insertUser('eric', 'passwd', 'user', null, 1, 'harf-line-learn', '1', '偉人', 'Eric Chiou', 'eric@example.com', null); + * + * echo 'Finish'; + * } + * + * + * // 若設定的DBMS不被支援 則丟出例外 + * catch (Database\Exception\DatabaseNoSupportException $e) { + * echo 'No Support in ', $e->getType(); + * } catch (Exception $e) { + * echo 'Caught other exception: ', $e->getMessage(); + * echo '

    '. $e->getCode() .'

    '; + * } + * + * @param string $uId 使用者名稱 + * @param string $password 密碼 + * @param string $gId 群組 + * @param string $cId 班級 + * @param string $enable 啟用此帳號 + * @param string $l_mode 學習模式 + * @param string $m_mode 教材模式 + * @param string $nickName 暱稱 + * @param string $realName 姓名 + * @param string $email 電子郵件地址 + * @param string $memo 備註 + */ + public function insertUser($uId, $password, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo){ + + // 檢查是否有支援所設定的DBMS + //if($this->db_type == 'mysql') { + + //紀錄使用者帳號進資料庫 + $sqlString = "INSERT INTO ".$this->table('User'). + " (`UID`, `UPassword`, `GID`, `CID`, `UEnabled`, `UBuild_Time`, + `LMode`, `MMode`, `UNickname`, `UReal_Name`, `UEmail`, `UMemo`) + VALUES ( :id , :passwd, :gid , :cid , :enable , NOW() , + :lmode , :mmode , :nickname , :realname , :email , :memo )"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $uId); + $query->bindParam(":passwd", $password); + $query->bindParam(":gid", $gId); + $query->bindParam(":cid", $cId); + $query->bindParam(":enable", $enable); + $query->bindParam(":lmode", $l_mode); + $query->bindParam(":mmode", $m_mode); + $query->bindParam(":nickname", $nickName); + $query->bindParam(":realname", $realName); + $query->bindParam(":email", $email); + $query->bindParam(":memo", $memo); + $query->execute(); + //} + //else { + // throw new Exception\DatabaseNoSupportException($this->db_type); + //} + + } + + /** + * 移除一位使用者 + * @param string $uId 使用者名稱 + */ + public function deleteUser($uId) { + + //if($this->db_type == 'mysql') { + $sqlString = "DELETE FROM ".$this->table(self::FORM_USER). + " WHERE `UID` = :id "; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $uId); + $query->execute(); + //} + //else { + // throw new Exception\DatabaseNoSupportException($this->db_type); + //} + } + + /** + * 查詢一位使用者帳號資料 + * + * + * 範例: + * + * require_once __DIR__.'/../config.php'; + * require_once UELEARNING_LIB_ROOT.'/Database/DBUser.php'; + * use UElearning\Database; + * + * try { + * $db = new Database\DBUser(); + * + * $userInfo = $db->queryUser('yuan'); + * echo '
    '; print_r($userInfo); echo '
    '; + * } + * + * + * // 若設定的DBMS不被支援 則丟出例外 + * catch (Database\Exception\DatabaseNoSupportException $e) { + * echo 'No Support in ', $e->getType(); + * } catch (Exception $e) { + * echo 'Caught other exception: ', $e->getMessage(); + * echo '

    '. $e->getCode() .'

    '; + * } + * + * @param string $uId 使用者名稱 + * @return array 使用者資料陣列,格式為: + * array( + * 'user_id' => <帳號名稱>, + * 'password' => <密碼>, + * 'group_id' => <群組>, + * 'class_id' => <班級>, + * 'enable' => <啟用>, + * 'build_time' => <建立日期>, + * 'learnStyle_mode' => <偏好學習導引模式>, + * 'material_mode' => <偏好教材模式>, + * 'nickname' => <暱稱>, + * 'realname' => <真實姓名>, + * 'email' => <電子郵件地址>, + * 'memo' => <備註> + * ); + * + */ + public function queryUser($uId) { + + $sqlString = "SELECT * FROM ".$this->table('User'). + " WHERE `UID` = :uid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':uid', $uId); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + $queryResult = $queryResultAll[0]; + + if($queryResult['UEnabled'] != '0') { + $output_enable = true; + } + else { $output_enable = false; } + + $result = array( + 'user_id' => $queryResult['UID'], + 'password' => $queryResult['UPassword'], + 'group_id' => $queryResult['GID'], + 'class_id' => $queryResult['CID'], + 'enable' => $output_enable, + 'build_time' => $queryResult['UBuild_Time'], + 'learnStyle_mode' => $queryResult['LMode'], + 'material_mode' => $queryResult['MMode'], + 'nickname' => $queryResult['UNickname'], + 'realname' => $queryResult['UReal_Name'], + 'email' => $queryResult['UEmail'], + 'memo' => $queryResult['UMemo'] + ); + + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 查詢所有的使用者帳號資料 + * + * @return array 使用者資料陣列,格式為: + * + * array( + * array( + * 'user_id' => <帳號名稱>, + * 'password' => <密碼>, + * 'group_id' => <群組>, + * 'class_id' => <班級>, + * 'enable' => <啟用>, + * 'build_time' => <建立日期>, + * 'learnStyle_mode' => <偏好學習導引模式>, + * 'material_mode' => <偏好教材模式>, + * 'nickname' => <暱稱>, + * 'realname' => <真實姓名>, + * 'email' => <電子郵件地址>, + * 'memo' => <備註> + * ) + * ); + * + */ + public function queryAllUser() { + + $sqlString = "SELECT * FROM ".$this->table('User'); + + $query = $this->connDB->prepare($sqlString); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + // 製作回傳結果陣列 + $result = array(); + foreach($queryResultAll as $key => $thisResult) { + + if($thisResult['UEnabled'] != '0') { + $output_enable = true; + } + else { $output_enable = false; } + + array_push($result, + array( 'user_id' => $thisResult['UID'], + 'password' => $thisResult['UPassword'], + 'group_id' => $thisResult['GID'], + 'class_id' => $thisResult['CID'], + 'enable' => $output_enable, + 'build_time' => $thisResult['UBuild_Time'], + 'learnStyle_mode' => $thisResult['LMode'], + 'material_mode' => $thisResult['MMode'], + 'nickname' => $thisResult['UNickname'], + 'realname' => $thisResult['UReal_Name'], + 'email' => $thisResult['UEmail'], + 'memo' => $thisResult['UMemo']) + ); + } + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 修改一位使用者的資料內容 + * + * 範例: + * + * $db = new Database\DBUser(); + * $db->changeUserData('yuan', 'memo', 'hahaha'); + * + * @param string $uId 使用者名稱 + * @param string $field 欄位名稱 + * @param string $value 內容 + */ + public function changeUserData($uId, $field, $value) { + // UPDATE `UElearning`.`chu__User` SET `UMemo` = '測試者' WHERE `chu__User`.`UID` = 'yuan'; + + $sqlField = null; + switch($field) { + case 'user_id': $sqlField = 'UID'; break; + case 'password': $sqlField = 'UPassword'; break; + case 'group_id': $sqlField = 'GID'; break; + case 'class_id': $sqlField = 'CID'; break; + case 'enable': $sqlField = 'UEnabled'; break; + case 'build_time': $sqlField = 'UBuild_Time'; break; + case 'learnStyle_mode': $sqlField = 'LMode'; break; + case 'material_mode': $sqlField = 'MMode'; break; + case 'nickname': $sqlField = 'UNickname'; break; + case 'realname': $sqlField = 'UReal_Name'; break; + case 'email': $sqlField = 'UEmail'; break; + case 'memo': $sqlField = 'UMemo'; break; + default: $sqlField = $field; break; + } + + + $sqlString = "UPDATE ".$this->table('User'). + " SET `".$sqlField."` = :value". + " WHERE `UID` = :uid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':uid', $uId); + $query->bindParam(':value', $value); + $query->execute(); + } + + // ======================================================================== + + /** + * 插入群組資料 + * + * @param string $gId 群組ID + * @param string $name 群組顯示名稱 + * @param string $memo 備註 + * @param string $auth_admin Server端管理權 + * @param string $auth_clientAdmin Client端管理權 + */ + public function insertGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin) { + + // 紀錄使用者帳號進資料庫 + $sqlString = "INSERT INTO ".$this->table('AGroup'). + " (`GID`, `GName`, `GMemo`, `GBuild_Time`, `GAuth_Admin`, `GAuth_ClientAdmin`) + VALUES ( :id , :name, :memo , NOW(), :auth_admin , :auth_clientAdmin )"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $gId); + $query->bindParam(":name", $name); + $query->bindParam(":memo", $memo); + $query->bindParam(":auth_admin", $auth_admin); + $query->bindParam(":auth_clientAdmin", $auth_clientAdmin); + $query->execute(); + } + + /** + * 移除一個使用者群組 + * @param string $gId + */ + public function deleteGroup($gId) { + + $sqlString = "DELETE FROM ".$this->table('AGroup'). + " WHERE `GID` = :id "; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $gId); + $query->execute(); + } + + /** + * 查詢一個使用者群組資料 + * + * @return array 使用者群組資料陣列,格式為: + * + * array( 'group_id' => <群組ID>, + * 'name' => <群組顯示名稱>, + * 'memo' => <備註>, + * 'auth_admin' => , + * 'auth_clientAdmin' => + * ); + * + */ + public function queryGroup($gId) { + + $sqlString = "SELECT * FROM ".$this->table('AGroup'). + " WHERE `GID` = :gid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':gid', $gId); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + $thisResult = $queryResultAll[0]; + + // 轉換成boolean + if($thisResult['GAuth_Admin'] != '0') { + $output_auth_admin = true; + } else { $output_auth_admin = false; } + + if($thisResult['GAuth_ClientAdmin'] != '0') { + $output_auth_clientAdmin = true; + } else { $output_auth_clientAdmin = false; } + + // 製作回傳結果陣列 + $result = array('group_id' => $thisResult['GID'], + 'name' => $thisResult['GName'], + 'memo' => $thisResult['GMemo'], + 'build_time' => $thisResult['GBuild_Time'], + 'auth_admin' => $output_auth_admin, + 'auth_clientAdmin' => $output_auth_clientAdmin + ); + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 查詢所有的使用者群組資料 + * + * @return array 使用者群組資料陣列,格式為: + * + * array( + * array( + * 'group_id' => <群組ID>, + * 'name' => <群組顯示名稱>, + * 'memo' => <備註>, + * 'auth_admin' => , + * 'auth_clientAdmin' => + * ) + * ); + * + */ + public function queryAllGroup() { + + $sqlString = "SELECT * FROM ".$this->table('AGroup'); + + $query = $this->connDB->prepare($sqlString); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + // 製作回傳結果陣列 + $result = array(); + foreach($queryResultAll as $key => $thisResult) { + + // 轉換成boolean + if($thisResult['GAuth_Admin'] != '0') { + $output_auth_admin = true; + } else { $output_auth_admin = false; } + + if($thisResult['GAuth_ClientAdmin'] != '0') { + $output_auth_clientAdmin = true; + } else { $output_auth_clientAdmin = false; } + + // 插入一筆資料 + array_push($result, + array( 'group_id' => $thisResult['GID'], + 'name' => $thisResult['GName'], + 'memo' => $thisResult['GMemo'], + 'build_time' => $thisResult['GBuild_Time'], + 'auth_admin' => $output_auth_admin, + 'auth_clientAdmin' => $output_auth_clientAdmin) + ); + } + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 修改一個群組的資料內容 + * + * 範例: + * + * $db = new Database\DBUser(); + * $db->changeGroupData('student', 'name', '學生'); + * + * @param string $gId 群組ID + * @param string $field 欄位名稱 + * @param string $value 內容 + */ + public function changeGroupData($gId, $field, $value) { + // UPDATE `UElearning`.`chu__User` SET `UMemo` = '測試者' WHERE `chu__User`.`UID` = 'yuan'; + + $sqlField = null; + switch($field) { + case 'group_id': $sqlField = 'UID'; break; + case 'name': $sqlField = 'GName'; break; + case 'memo': $sqlField = 'GMemo'; break; + case 'auth_admin': $sqlField = 'GAuth_Admin'; break; + case 'auth_clientAdmin': $sqlField = 'GAuth_ClientAdmin'; break; + default: $sqlField = $field; break; + } + + + $sqlString = "UPDATE ".$this->table('AGroup'). + " SET `".$sqlField."` = :value". + " WHERE `GID` = :gid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':gid', $gId); + $query->bindParam(':value', $value); + $query->execute(); + } + + // ======================================================================== + + /** + * 插入班級資料 + * + * @param string $cId 班級ID + * @param string $name 班級顯示名稱 + * @param string $memo 備註 + * @return int 剛剛新增的ID + */ + public function insertClassGroup($cId, $name, $memo) { + + // 紀錄使用者帳號進資料庫 + $sqlString = "INSERT INTO ".$this->table('CGroup'). + " (`CID`, `CName`, `CMemo`, `CBuild_Time`) + VALUES ( :id , :name, :memo , NOW() )"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $cId); + $query->bindParam(":name", $name); + $query->bindParam(":memo", $memo); + $query->execute(); + + // 取得剛剛加入的ID + $sqlString = "SELECT LAST_INSERT_ID()"; + $query = $this->connDB->query($sqlString); + $queryResult = $query->fetch(); + return $queryResult[0]; + } + + /** + * 移除一個班級 + * @param string $cId + */ + public function deleteClassGroup($cId) { + + $sqlString = "DELETE FROM ".$this->table('CGroup'). + " WHERE `CID` = :id "; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":id", $cId); + $query->execute(); + } + + /** + * 查詢一個班級資料 + * + * @return array 班級資料陣列,格式為: + * + * array( 'class_id' => <班級ID>, + * 'name' => <班級顯示名稱>, + * 'memo' => <備註>, + * 'build_time' => <建立時間> + * ); + * + */ + public function queryClassGroup($cId) { + + $sqlString = "SELECT * FROM ".$this->table('CGroup'). + " WHERE `CID` = :cid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':cid', $cId); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + $thisResult = $queryResultAll[0]; + // 製作回傳結果陣列 + $result = array('class_id' => $thisResult['CID'], + 'name' => $thisResult['CName'], + 'memo' => $thisResult['CMemo'], + 'build_time' => $thisResult['CBuild_Time'] + ); + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 查詢所有的班級資料 + * + * @return array 班級資料陣列,格式為: + * + * array( + * array( + * 'class_id' => <班級ID>, + * 'name' => <班級顯示名稱>, + * 'memo' => <備註>, + * 'build_time' => <建立時間> + * ) + * ); + * + */ + public function queryAllClassGroup() { + + $sqlString = "SELECT * FROM ".$this->table('CGroup'); + + $query = $this->connDB->prepare($sqlString); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + // 製作回傳結果陣列 + $result = array(); + foreach($queryResultAll as $key => $thisResult) { + array_push($result, + array( 'class_id' => $thisResult['CID'], + 'name' => $thisResult['CName'], + 'memo' => $thisResult['CMemo'], + 'build_time' => $thisResult['CBuild_Time']) + ); + } + return $result; + } + // 若都沒查到的話 + else { + return null; + } + } + + /** + * 修改一個群組的資料內容 + * + * 範例: + * + * $db = new Database\DBUser(); + * $db->changeClassGroupData(2, 'name', '五年一班'); + * + * @param string $cId 班級ID + * @param string $field 欄位名稱 + * @param string $value 內容 + */ + public function changeClassGroupData($cId, $field, $value) { + + $sqlField = null; + switch($field) { + case 'class_id': $sqlField = 'CID'; break; + case 'name': $sqlField = 'CName'; break; + case 'memo': $sqlField = 'CMemo'; break; + default: $sqlField = $field; break; + } + + + $sqlString = "UPDATE ".$this->table('CGroup'). + " SET `".$sqlField."` = :value". + " WHERE `CID` = :cid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':cid', $cId); + $query->bindParam(':value', $value); + $query->execute(); + } + + /** + * 設定自動編號的起始值 + * @param int $num 自動編號起始值 + */ + public function setClassGroupIDAutoIncrement($num) { + + // TODO: 不帶值的話,以最後編號為起頭 + $sqlString = "ALTER TABLE ".$this->table('CGroup'). + " AUTO_INCREMENT = $num"; + + $this->connDB->exec($sqlString); + } +} \ No newline at end of file diff --git a/htdocs/lib/Database/DBUserSession.php b/htdocs/lib/Database/DBUserSession.php new file mode 100644 index 0000000..48d85a3 --- /dev/null +++ b/htdocs/lib/Database/DBUserSession.php @@ -0,0 +1,210 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage Database + */ +class DBUserSession extends Database { + + /** + * 新增登入資料 + * @param string $token 登入token + * @param string $uId 帳號ID + * @param string $agent 登入所使用的裝置 + */ + public function login($token, $uId, $agent) { + + //紀錄登入階段進資料庫 + $sqlString = "INSERT INTO ".$this->table('UserSession'). + " (`UsID`, `UToken`, `UID`, `UAgent`, `ULoginDate`, `ULogoutDate`) + VALUES (NULL , :token, :uid , :agent , NOW() , NULL)"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":token", $token); + $query->bindParam(":uid", $uId); + $query->bindParam(":agent", $agent); + $query->execute(); + } + + /** + * 標注此登入階段為登出 + * @param string $token 登入token + */ + public function logout($token) { + + $sqlString = "UPDATE ".$this->table('UserSession'). + " SET `UToken` = NULL, `ULogoutDate` = NOW() + WHERE `UToken` = :token"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":token", $token); + $query->execute(); + } + + /** + * 標注此帳號所有的登入階段為登出 + * @param string $uid 帳號ID + * @return int 修改幾筆資料 + */ + public function logoutByUserId($uid) { + + $sqlString = "UPDATE ".$this->table('UserSession'). + " SET `UToken` = NULL, `ULogoutDate` = NOW() + WHERE `UID` = :uid AND `UToken` IS NOT NULL"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(":uid", $uid); + $query->execute(); + return $query->rowCount(); + } + + /** + * 以token查詢 + * @param string $token 登入token + * @return array 登入階段資料陣列,格式為: + * array( + * 'session_id' => <登入編號>, + * 'token' => <登入Token>, + * 'user_id' => <使用者>, + * 'agent' => <用哪個裝置登入>, + * 'login_date' => <登入時間>, + * 'logout_date' => <登出時間> + * ); + */ + public function queryByToken($token) { + $sqlString = "SELECT * FROM ".$this->table('UserSession'). + " WHERE `UToken` = :token"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':token', $token); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + $queryResult = $queryResultAll[0]; + + $result = array( + 'session_id' => $queryResult['UsID'], + 'token' => $queryResult['UToken'], + 'user_id' => $queryResult['UID'], + 'agent' => $queryResult['UAgent'], + 'login_date' => $queryResult['ULoginDate'], + 'logout_date' => $queryResult['ULogoutDate'] + ); + + return $result; + } + else return null; + } + + /** + * 以使用者ID查詢 + * @param string $uId 使用者ID + * @return array 登入階段資料陣列,格式為: + * array( + * array( + * 'session_id' => <登入編號>, + * 'token' => <登入Token>, + * 'user_id' => <使用者>, + * 'agent' => <用哪個裝置登入>, + * 'login_date' => <登入時間>, + * 'logout_date' => <登出時間> + * ) + * ); + */ + public function queryByUserId($uId) { + $sqlString = "SELECT * FROM ".$this->table('UserSession'). + " WHERE `UID` = :uid"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':uid', $uId); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + + // 製作回傳結果陣列 + $result = array(); + foreach($queryResultAll as $key => $thisResult) { + array_push($result, + array( + 'session_id' => $thisResult['UsID'], + 'token' => $thisResult['UToken'], + 'user_id' => $thisResult['UID'], + 'agent' => $thisResult['UAgent'], + 'login_date' => $thisResult['ULoginDate'], + 'logout_date' => $thisResult['ULogoutDate'] + ) + ); + } + return $result; + } + else return null; + } + + /** + * 以使用者ID查詢,目前所有已登入的登入階段 + * @param string $uId 使用者ID + * @return array 登入階段資料陣列,格式為: + * array( + * array( + * 'session_id' => <登入編號>, + * 'token' => <登入Token>, + * 'user_id' => <使用者>, + * 'agent' => <用哪個裝置登入>, + * 'login_date' => <登入時間>, + * 'logout_date' => <登出時間> + * ) + * ); + */ + public function queryLoginByUserId($uId) { + $sqlString = "SELECT * FROM ".$this->table('UserSession'). + " WHERE `UID` = :uid AND `UToken` IS NOT NULL"; + + $query = $this->connDB->prepare($sqlString); + $query->bindParam(':uid', $uId); + $query->execute(); + + $queryResultAll = $query->fetchAll(); + // 如果有查到一筆以上 + if( count($queryResultAll) >= 1 ) { + + // 製作回傳結果陣列 + $result = array(); + foreach($queryResultAll as $key => $thisResult) { + array_push($result, + array( + 'session_id' => $thisResult['UsID'], + 'token' => $thisResult['UToken'], + 'user_id' => $thisResult['UID'], + 'agent' => $thisResult['UAgent'], + 'login_date' => $thisResult['ULoginDate'], + 'logout_date' => $thisResult['ULogoutDate'] + ) + ); + } + return $result; + } + else return null; + } + +} \ No newline at end of file diff --git a/htdocs/lib/Database/Database.php b/htdocs/lib/Database/Database.php new file mode 100644 index 0000000..ac5de92 --- /dev/null +++ b/htdocs/lib/Database/Database.php @@ -0,0 +1,173 @@ + 'mysql', + * 'host' => 'localhost', + * 'port' => '3306', + * 'user' => 'user', + * 'password' => '123456', + * 'dbname' => 'chu-elearning', + * 'prefix' => 'chu_' + * )); + * + * 實際範例可參考 `DBAdmin` 類別的說明文件 + * + * @author Yuan Chiu + * @version 2.0.0 + * @package UElearning + * @subpackage Database + */ +abstract class Database { + + /** + * 資料庫伺服器類型 + * + * 目前支援的: + * * mysql + * + * @type string + */ + protected $db_type; + + /** + * 資料庫伺服器位址 + * @type string + */ + protected $db_host; + + /** + * 資料庫伺服器連結埠 + * @type string + */ + protected $db_port; + + /** + * 資料庫帳號 + * @type string + */ + protected $db_user; + + /** + * 資料庫密碼 + * @type string + */ + protected $db_passwd; + + /** + * 資料庫名稱 + * @type string + */ + protected $db_name; + + /** + * 資料表前綴字元 + * @type string + */ + protected $db_prefix; + + // ------------------------------------------------------------------------ + + /** + * 資料庫連結物件 + * @type UElearning\Database\PDODB + */ + protected $connDB; + + // ======================================================================== + + /** + * 連接資料庫 + * + * @param array $conf (optional) 資料庫相關參數,格式為: + * array( 'type' => 'mysql', + * 'host' => 'localhost', + * 'port' => '3306', + * 'user' => 'user', + * 'password' => '123456', + * 'dbname' => 'chu-elearning', + * 'prefix' => 'chu_' ) + * 若不填寫將會直接使用設定在`config.php`的常數 + * + * @throws UElearning\Database\Exception\DatabaseNoSupportException + * @author Yuan Chiu + * @since 2.0.0 + */ + public function __construct($conf = null) { + + // 將資料庫設定資訊帶入 + if(isset($conf)) { + $this->db_type = $conf['type']; + $this->db_host = $conf['host']; + $this->db_port = $conf['port']; + $this->db_user = $conf['user']; + $this->db_passwd = $conf['password']; + $this->db_name = $conf['dbname']; + $this->db_prefix = $conf['prefix']; + } + else { + $this->db_type = DB_TYPE; + $this->db_host = DB_HOST; + $this->db_port = DB_PORT; + $this->db_user = DB_USER; + $this->db_passwd = DB_PASS; + $this->db_name = DB_NAME; + $this->db_prefix = DB_PREFIX; + } + + // 檢查是否有支援所設定的DBMS + if($this->db_type == 'mysql') { + $this->connDB = new MySQLDB($this->db_name + , $this->db_host + , $this->db_port + , $this->db_user + , $this->db_passwd); + } + else { + throw new Exception\DatabaseNoSupportException($this->db_type); + } + } + + /** + * 轉為完整的資料表名稱(包含前綴字元) + * + * @param string $tableName 資料表名稱 + * @return string 完整的資料表名稱 + * + * @author Yuan Chiu + * @since 2.0.0 + */ + public function table($tableName) { + return $this->db_prefix.$tableName; + } + + /** + * 測試資料庫有無連接成功 + * + * @since 2.0.0 + */ + public function connectTest() { + // TODO: Fill code in + + } +} \ No newline at end of file diff --git a/htdocs/lib/Database/Exception.php b/htdocs/lib/Database/Exception.php new file mode 100644 index 0000000..dff099d --- /dev/null +++ b/htdocs/lib/Database/Exception.php @@ -0,0 +1,37 @@ +type = $type; + parent::__construct('No support: '.$this->type); + } + + /** + * 取得輸入的資料庫系統名稱 + * @return string 錯誤訊息內容 + */ + public function getType() { + return $this->type; + } +} + diff --git a/htdocs/lib/Database/MySQLDB.php b/htdocs/lib/Database/MySQLDB.php new file mode 100644 index 0000000..89be3dd --- /dev/null +++ b/htdocs/lib/Database/MySQLDB.php @@ -0,0 +1,71 @@ + + * @version 2.0.0 + * @see https://github.com/shuliu/myPDO + * @package UElearning + * @subpackage Database + */ +class MySQLDB extends PDO { + + /** + * 連結資料庫 + * + * @param string $dbname 資料庫名稱 + * @param string $host 資料庫伺服器位址 + * @param int $port 資料庫伺服器連接埠 + * @param string $user 資料庫伺服器帳號 + * @param string $passwd 資料庫伺服器密碼 + * @author Yuan Chiu + * @since 2.0.0 + */ + public function __construct($dbname, $host, $port, $user, $passwd){ + parent::__construct('mysql:dbname='.$dbname + .';host:'.$host.';port='.$port + .';charset=utf8', DB_USER, DB_PASS); + + //配合PHP< 5.3.6 PDO沒有charset用的 + //參考: http://gdfan1114.wordpress.com/2013/06/24/php-5-3-6-%E7%89%88-pdo-%E9%85%8D%E5%90%88%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99%E5%BA%AB%E6%99%82%E7%9A%84%E4%B8%AD%E6%96%87%E5%95%8F%E9%A1%8C/ + $this->exec('set names utf8'); + + } + + // ======================================================================== + /** + * 錯誤訊息的陣列 + * + * 改寫Adodb -> ErrorMsg + * + * @access public + * @return array 錯誤訊息 + * + * @since 2.0.0 + * @author shuliu + * @see https://github.com/shuliu/myPDO/blob/master/PDO.class.php + */ + public function errorMsg(){ + $err = parent ::errorinfo(); + if( $err[0]!='00000' ){ + return array('errorCode'=>$err[0] + ,'number'=>$err[1] + ,'message'=>$err[2]); + }else{ + return null; + } + } + + } diff --git a/htdocs/lib/Database/NOTE.md b/htdocs/lib/Database/NOTE.md new file mode 100644 index 0000000..7f17973 --- /dev/null +++ b/htdocs/lib/Database/NOTE.md @@ -0,0 +1,8 @@ +Database +=== + +## 全域變數 +* DB_NAME +* DB_HOST +* DB_USER +* DB_PASS \ No newline at end of file diff --git a/htdocs/lib/Exception.php b/htdocs/lib/Exception.php new file mode 100644 index 0000000..aace491 --- /dev/null +++ b/htdocs/lib/Exception.php @@ -0,0 +1,52 @@ +fieldName = $fieldName; + parent::__construct(); + } + else { + $this->fieldName = array(); + } + } + + /** + * 新增一項未輸入的欄位名稱 + */ + public function addFieldName($fieldName) { + $this->fieldName += array($fieldName); + } + + /** + * 取得未輸入的欄位名稱 + * @return string|array 欄位名稱 + */ + public function getFieldName() { + return $this->fieldName; + } +} diff --git a/htdocs/lib/User/ClassGroup.php b/htdocs/lib/User/ClassGroup.php new file mode 100644 index 0000000..52aaf56 --- /dev/null +++ b/htdocs/lib/User/ClassGroup.php @@ -0,0 +1,167 @@ +getName(); + * $group->setName('測試用'); + * echo $group->getName(); + * } + * catch (User\Exception\ClassNoFoundException $e) { + * echo 'No Found class: '. $e->getGroupId(); + * } + * + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class ClassGroup { + + /** + * 群組ID + * @type int + */ + protected $cId; + + // ======================================================================== + + /** + * 查詢到此帳號的所有資訊的結果 + * + * 由 $this->getQuery() 抓取資料表中所有資訊,並放在此陣列裡 + * + * @type array + */ + protected $queryResultArray; + + /** + * 從資料庫取得此群組查詢 + * + * @throw UElearning\User\Exception\ClassNoFoundException + * @since 2.0.0 + */ + protected function getQuery(){ + + // 從資料庫查詢群組 + $db = new Database\DBUser(); + $groupInfo = $db->queryClassGroup($this->cId); + + // 判斷有沒有這個群組 + if( $groupInfo != null ) { + $this->queryResultArray = $groupInfo; + } + else throw new Exception\ClassNoFoundException($this->cId); + } + + /** + * 從資料庫更新此群組設定 + * + * @since 2.0.0 + */ + protected function setUpdate($field, $value){ + + // 將新設定寫進資料庫裡 + $db = new Database\DBUser(); + $db->changeClassGroupData($this->cId, $field, $value); + $this->getQuery(); + } + + // ======================================================================== + + /** + * 建構子 + * + * @param int $inputCID 班級ID + * @since 2.0.0 + */ + public function __construct($inputCID){ + $this->cId = $inputCID; + $this->getQuery(); + } + + // ======================================================================== + + /** + * 取得群組ID + * + * @return int 班級ID + * @since 2.0.0 + */ + public function getID(){ + return $this->cId; + } + + // ------------------------------------------------------------------------ + + /** + * 取得帳號建立時間 + * + * @return string 建立時間 + * @since 2.0.0 + */ + public function getCreateTime(){ + return $this->queryResultArray['build_time']; + } + // ======================================================================== + + /** + * 取得群組顯示名稱 + * + * @return string 群組名稱 + * @since 2.0.0 + */ + public function getName(){ + return $this->queryResultArray['name']; + } + + /** + * 設定群組顯示名稱 + * + * @param string $name 群組名稱 + * @since 2.0.0 + */ + public function setName($name){ + $this->setUpdate('name', $name); + } + + /** + * 取得帳號備註資訊 + * + * @return string 使用者帳號備註資訊 + * @since 2.0.0 + */ + public function getMemo(){ + return $this->queryResultArray['memo']; + } + + /** + * 修改帳號備註資訊 + * + * @param string $input 新的帳號備註資訊 + * @since 2.0.0 + */ + public function setMemo($input){ + $this->setUpdate('memo', $input); + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/ClassGroupAdmin.php b/htdocs/lib/User/ClassGroupAdmin.php new file mode 100644 index 0000000..fe472d5 --- /dev/null +++ b/htdocs/lib/User/ClassGroupAdmin.php @@ -0,0 +1,145 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class ClassGroupAdmin { + + /** + * 建立班級 + * + * 建立班級群組範例: + * + * try { + * $groupAdmin = new User\ClassGroupAdmin(); + * $newId = null; + * $newId = $groupAdmin->create( + * array( 'name' => '學生', + * 'memo' => null + * )); + * echo '你剛建立:'.$newId; + * } + * // 若已有重複班級ID + * catch (User\Exception\ClassIdExistException $e) { + * echo 'Is exist class: ', $e->getGroupId(); + * } + * + * @param array $classGroupArray 班級群組資訊陣列,格式為: + * array( 'class_id' => 12, + * 'name' => '學生', + * 'memo' => null ) + * @return int 剛剛新增進去的ID + * @throw UElearning\User\Exception\ClassIdExistException + * @since 2.0.0 + */ + public function create($classGroupArray) { + + // 檢查有無填寫 + if(isset($classGroupArray)) { + + // 若此id已存在 + if( isset($classGroupArray['class_id']) && + $this->isExist($classGroupArray['class_id']) ) { + + throw new Exception\ClassIdExistException( + $classGroupArray['class_id'] ); + } + // 沒有問題 + else { + // 處理未帶入的資料 + if( !isset($classGroupArray['class_id']) ){ + $classGroupArray['class_id'] = null; + } + + // 處理未帶入的資料 + if( !isset($classGroupArray['name']) ){ + $classGroupArray['name'] = null; + } + // 處理未帶入的資料 + if( !isset($classGroupArray['memo']) ){ + $classGroupArray['memo'] = null; + } + + // 新增一筆使用者資料進資料庫 + $db = new Database\DBUser(); + $id = $db->insertClassGroup( + $classGroupArray['class_id'], + $classGroupArray['name'], + $classGroupArray['memo'] + ); + + // 回傳剛剛新增的ID + return $id; + } + } + else throw Exception\NoDataException(); + } + + /** + * 是否已有相同名稱的班級ID + * + * @param int $class_id 班級ID + * @return bool 已有相同的班級ID + * @since 2.0.0 + */ + public function isExist($class_id) { + + $db = new Database\DBUser(); + $info = $db->queryClassGroup($class_id); + + if( $info != null ) return true; + else return false; + } + + /** + * 移除此班級 + * + * 範例: + * + * try { + * $groupAdmin = new User\ClassGroupAdmin(); + * $groupAdmin->remove(2); + * + * } + * catch (User\Exception\ClassNoFoundException $e) { + * echo 'No Found class: ', $e->getGroupId(); + * } + * + * @param int $class_id 班級ID + * @throw UElearning\User\Exception\ClassNoFoundException + * @since 2.0.0 + */ + public function remove($class_id) { + + // 若有此使用者 + if($this->isExist($class_id)) { + + // TODO: 檢查所有關聯的資料,確認是否可以移除 + + // 移除資料庫中的使用者 + $db = new Database\DBUser(); + $db->deleteClassGroup($class_id); + } + // 若沒有這位使用者 + else { + throw new Exception\ClassNoFoundException($class_id); + } + + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/Exception.php b/htdocs/lib/User/Exception.php new file mode 100644 index 0000000..f24ae2e --- /dev/null +++ b/htdocs/lib/User/Exception.php @@ -0,0 +1,276 @@ +userId = $userId; + parent::__construct($description); + } + + /** + * 取得輸入的資料庫系統名稱 + * @return string 錯誤訊息內容 + */ + public function getUserId() { + return $this->userId; + } +} + +// 使用者登入 ====================================================================== +/** + * 沒有找到此帳號 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserNoFoundException extends UserException { + /** + * 沒有找到此帳號 + * @param string $userId 輸入的使用者名稱 + */ + public function __construct($userId) { + parent::__construct($userId, 'User: "'.$userId.'" is no found.'); + } +} + +/** + * 使用者登入密碼錯誤 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserPasswordErrException extends UserException { + /** + * 沒有找到此帳號 + * @param string $userId 輸入的使用者名稱 + */ + public function __construct($userId) { + parent::__construct($userId, 'User: "'.$userId.'" password is wrong.'); + } +} + +/** + * 此帳號未啟用 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserNoActivatedException extends UserException { + /** + * 此帳號未啟用 + * @param string $userId 輸入的使用者名稱 + */ + public function __construct($userId) { + parent::__construct($userId, 'User: "'.$userId.'" is no activated.'); + } +} + +// 建立使用者 ====================================================================== +/** + * 已有重複的使用者名稱 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserIdExistException extends UserException { + /** + * 已有重複的使用者名稱 + * @param string $userId 輸入的使用者名稱 + */ + public function __construct($userId) { + parent::__construct($userId, 'UserId: "'.$userId.'" is exist.'); + } +} + +// ============================================================================ + +/** + * 使用者群組例外 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +abstract class GroupException extends \UnexpectedValueException { + + /** + * 指定的使用者群組ID + * @type string + */ + private $groupId; + + /** + * 使用者帳號例外 + * @param string $groupId 輸入的使用者群組ID + * @param string $description 描述 + */ + public function __construct($groupId, $description) { + $this->groupId = $groupId; + parent::__construct($description); + } + + /** + * 取得輸入的資料庫系統名稱 + * @return string 錯誤訊息內容 + */ + public function getGroupId() { + return $this->groupId; + } +} + +/** + * 已有重複的使用者群組ID + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class GroupIdExistException extends GroupException { + /** + * 已有重複的使用者名稱 + * @param string $groupId 輸入的使用者群組ID + */ + public function __construct($groupId) { + parent::__construct($groupId, 'GroupId: "'.$groupId.'" is exist.'); + } +} + +/** + * 沒有找到此使用者群組ID + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class GroupNoFoundException extends GroupException { + /** + * 沒有找到此帳號 + * @param string $groupId 輸入的使用者群組ID + */ + public function __construct($groupId) { + parent::__construct($groupId, 'Group: "'.$groupId.'" is no found.'); + } +} + +// ============================================================================ + +/** + * 已有重複的使用者群組ID + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class ClassIdExistException extends GroupException { + /** + * 已有重複的使用者名稱 + * @param string $groupId 輸入的使用者群組ID + */ + public function __construct($groupId) { + parent::__construct($groupId, 'ClassId: "'.$groupId.'" is exist.'); + } +} + +/** + * 沒有找到此使用者群組ID + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class ClassNoFoundException extends GroupException { + /** + * 沒有找到此帳號 + * @param string $groupId 輸入的使用者群組ID + */ + public function __construct($groupId) { + parent::__construct($groupId, 'Class Group: "'.$groupId.'" is no found.'); + } +} + +// ============================================================================ + +/** + * 沒有此權限例外 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class PermissionNoFoundException extends \UnexpectedValueException { + + /** + * 指定的使用者群組ID + * @type string + */ + private $permissionName; + + /** + * 使用者帳號例外 + * @param string $groupId 輸入的使用者群組ID + * @param string $description 描述 + */ + public function __construct($permissionName) { + $this->permissionName = $permissionName; + parent::__construct('No Found Permission: '.$this->permissionName); + } + + /** + * 取得輸入的資料庫系統名稱 + * @return string 錯誤訊息內容 + */ + public function getName() { + return $this->permissionName; + } + +} + +// ============================================================================ + +/** + * 找不到此登入階段 + * @since 2.0.0 + * @package UElearning + * @subpackage User + */ +class LoginTokenNoFoundException extends \UnexpectedValueException { + + /** + * 登入階段Token + * @type string + */ + private $token; + + /** + * 找不到此登入階段例外 + * @param string $token 登入階段Token + */ + public function __construct($token) { + $this->token = $token; + parent::__construct('No Found Login Token: '.$this->token); + } + + /** + * 取得輸入的登入階段Token + * @return string 登入階段Token + */ + public function getToken() { + return $this->token; + } +} \ No newline at end of file diff --git a/htdocs/lib/User/NOTE.md b/htdocs/lib/User/NOTE.md new file mode 100644 index 0000000..8a60ff5 --- /dev/null +++ b/htdocs/lib/User/NOTE.md @@ -0,0 +1,11 @@ +User Package +=== + +## UserControl.php +登入使用者帳號所用的 + +## User.php + + +## UserAdmin.php +管理使用者帳號、管理群組 diff --git a/htdocs/lib/User/User.php b/htdocs/lib/User/User.php new file mode 100644 index 0000000..c459e01 --- /dev/null +++ b/htdocs/lib/User/User.php @@ -0,0 +1,526 @@ +changePassword('123456'); + * echo $user->isPasswordCorrect('123456'); + * + * echo 'NickName: '.$user->getNickName(); + * } + * catch (User\Exception\UserNoFoundException $e) { + * echo 'No Found user: '. $e->getUserId(); + * } + * + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class User { + + /** + * 使用者ID + * @type string + */ + protected $uId; + + // ------------------------------------------------------------------------ + + /** + * 查詢到此帳號的所有資訊的結果 + * + * 由 $this->getQuery() 抓取資料表中所有資訊,並放在此陣列裡 + * @type array + */ + protected $queryResultArray; + + /** + * 從資料庫取得此帳號查詢 + * + * @throw UElearning\User\Exception\UserNoFoundException + * @since 2.0.0 + */ + protected function getQuery(){ + // 從資料庫查詢使用者 + $db = new Database\DBUser(); + $userInfo = $db->queryUser($this->uId); + + // 判斷有沒有這位使用者 + if( $userInfo != null ) { + $this->queryResultArray = $userInfo; + } + else throw new Exception\UserNoFoundException($this->uId); + } + + /** + * 從資料庫更新此帳號設定 + * + * @since 2.0.0 + */ + protected function setUpdate($field, $value){ + /// 將新設定寫進資料庫裡 + $db = new Database\DBUser(); + $db->changeUserData($this->uId, $field, $value); + $this->getQuery(); + } + + // ======================================================================== + + /** + * 建構子 + * + * @param string $inputUID 使用者ID + * @since 2.0.0 + */ + public function __construct($inputUID){ + $this->uId = $inputUID; + $this->getQuery(); + } + + // ======================================================================== + + /** + * 取得帳號名稱 + * + * @return string 帳號名稱 + * @since 2.0.0 + */ + public function getId(){ + return $this->uId; + } + + /** + * 取得帳號名稱 + * + * @return string 帳號名稱 + * @since 2.0.0 + */ + public function getUsername(){ + return $this->uId; + } + + // ------------------------------------------------------------------------ + + /** + * 驗證密碼是否錯誤 + * + * @param string $inputPasswd 密碼 + * @return bool true:密碼正確,false:密碼錯誤 + * @since 2.0.0 + */ + public function isPasswordCorrect($inputPasswd){ + $passUtil = new Util\Password(); + $this_passwd = $this->queryResultArray['password']; + return $passUtil->checkSame($this_passwd, $inputPasswd); + } + + /** + * 更改密碼 + * + * @param string $newPasswd 新密碼 + * @param string $newPasswdMode 新密碼加密方式(可省略) + * @return string 狀態回傳 + * @since 2.0.0 + */ + public function changePassword($newPasswd){ + // 進行密碼加密 + $passUtil = new Util\Password(); + $passwdEncrypted = $passUtil->encrypt($newPasswd); + + // 將新密碼寫進資料庫裡 + $this->setUpdate('password', $passwdEncrypted); + } + + // ======================================================================== + + /** + * 取得帳號建立時間 + * + * @return string 建立時間 + * @since 2.0.0 + */ + public function getCreateTime(){ + return $this->queryResultArray['build_time']; + } + // ======================================================================== + + /** + * 取得所在群組 + * + * @return string 群組ID + * @since 2.0.0 + */ + public function getGroup(){ + return $this->queryResultArray['group_id']; + } + + /** + * 取得所在群組顯示名稱 + * + * @return string 群組名稱 + * @since 2.0.0 + */ + public function getGroupName(){ + + // 群組ID + $groupID = $this->queryResultArray['group_id']; + + // 取得群組名稱 + try { + $group = new User\UserGroup($groupID); + return $group->getName(); + } + catch (Exception\GroupNoFoundException $e) { + throw $e; + } + } + + /** + * 設定所在群組 + * + * 範例: + * + * try { + * $user = new User\User('yuan'); + * try { + * $user->setGroup('student'); + * } + * catch (User\Exception\GroupNoFoundException $e) { + * echo 'No Group to set: '. $e->getGroupId(); + * } + * echo $user->getGroup(); + * } + * catch (User\Exception\UserNoFoundException $e) { + * echo 'No Found user: '. $e->getUserId(); + * } + * + * @param string $toGroup 群組ID + * @since 2.0.0 + */ + public function setGroup($toGroup){ + + // 檢查有此群組 + $groupAdmin = new UserGroupAdmin(); + if($groupAdmin->isExist($toGroup)) { + $this->setUpdate('group_id', $toGroup); + } + else { + throw new Exception\GroupNoFoundException($toGroup); + } + } + + // ------------------------------------------------------------------------ + + /** + * 取得所在班級 + * + * @return string 班級ID + * @since 2.0.0 + */ + public function getClass(){ + return $this->queryResultArray['class_id']; + } + + /** + * 取得所在班級名稱 + * + * @return string 班級名稱 + * @since 2.0.0 + */ + public function getClassName(){ + // TODO: 取得所在群組顯示名稱 + // 群組ID + $classID = $this->queryResultArray['class_id']; + + // 檢查有此群組 + if(isset($classID)) { + // 取得群組名稱 + try { + $group = new ClassGroup($classID); + return $group->getName(); + } + catch (Exception\ClassNoFoundException $e) { + throw $e; + } + } + else return null; + } + + /** + * 設定所在班級 + * + * 範例: + * + * try { + * $user = new User\User('yuan'); + * + * try { + * $user->setClass(1); + * } + * catch (User\Exception\ClassNoFoundException $e) { + * echo 'No Class to set: '. $e->getGroupId(); + * } + * } + * catch (User\Exception\UserNoFoundException $e) { + * echo 'No Found user: '. $e->getUserId(); + * } + * + * @param string $toClass 班級ID + * @since 2.0.0 + */ + public function setClass($toClass){ + + // 檢查有此群組 + if(isset($toClass)) { + + $classGroupAdmin = new ClassGroupAdmin(); + if($classGroupAdmin->isExist($toClass)) { + $this->setUpdate('class_id', $toClass); + } + else { + throw new Exception\ClassNoFoundException($toGroup); + } + } + else { + $this->setUpdate('class_id', null); + } + + } + + // ======================================================================== + + /** + * 取得帳號啟用狀態 + * + * @return bool 是否已啟用 + * @since 2.0.0 + */ + public function isEnable(){ + return $this->queryResultArray['enable']; + } + + /** + * 設定帳號啟用狀態 + * + * @param bool $isActive 是否為啟用 + * @since 2.0.0 + */ + public function setEnable($isActive){ + // TODO: 防呆,至少一個帳號是啟用的 + + // 將新設定寫進資料庫裡 + $this->setUpdate('enable', $isActive); + } + + // ======================================================================== + + /** + * 取得這個人的學習導引風格 + * + * @return string 學習導引風格 + * @since 2.0.0 + */ + public function getLearnStyle(){ + // TODO: 取得這個人的學習導引風格 + } + + /** + * 設定這個人的學習導引風格 + * + * @param string $style 學習導引風格 + * @since 2.0.0 + */ + public function setLearnStyle($style){ + // TODO: 設定這個人的學習導引風格 + + + } + + /** + * 取得這個人的教材風格 + * + * @return string 教材風格 + * @since 2.0.0 + */ + public function getMaterialStyle(){ + // TODO: 取得這個人的教材風格 + } + + /** + * 設定這個人的教材風格 + * + * @param string $style 教材風格 + * @since 2.0.0 + */ + public function setMaterialStyle($style){ + // TODO: 設定這個人的教材風格 + + + } + + // ======================================================================== + + /** + * 取得名稱 + * + * @return string 依照有填入多少名字
    優先順序: 暱稱→真實名字→帳號名稱 + * @since 2.0.0 + */ + public function getName(){ + // TODO: 待修正-取得名稱 + if($this->getNickName() != "") { + return $this->getNickName(); + } + else if($this->getRealName() != "") { + return $this->getRealName(); + } + else { + return $this->getUsername(); + } + } + + // ------------------------------------------------------------------------ + + /** + * 取得暱稱 + * + * @return string 暱稱 + * @since 2.0.0 + */ + public function getNickName(){ + return $this->queryResultArray['nickname']; + } + + /** + * 修改暱稱 + * + * @param string $input 新暱稱 + * @since 2.0.0 + */ + public function setNickName($input){ + // 將新設定寫進資料庫裡 + $this->setUpdate('nickname', $input); + } + + // ------------------------------------------------------------------------ + + /** + * 取得真實姓名 + * + * @return string 真實姓名 + * @since 2.0.0 + */ + public function getRealName(){ + return $this->queryResultArray['realname']; + } + + /** + * 修改真實姓名 + * + * @param string $input 新真實姓名 + * @since 2.0.0 + */ + public function setRealName($input){ + // 將新設定寫進資料庫裡 + $this->setUpdate('realname', $input); + } + + // ------------------------------------------------------------------------ + + /** + * 取得帳號Email + * + * @return string 使用者資訊的Email + * @since 2.0.0 + */ + public function getEmail(){ + return $this->queryResultArray['email']; + } + + /** + * 修改帳號Email + * + * @param string $input 新Email + * @since 2.0.0 + */ + public function setEmail($input){ + // 將新設定寫進資料庫裡 + $this->setUpdate('email', $input); + } + + // ------------------------------------------------------------------------ + + /** + * 取得帳號備註資訊 + * + * @return string 使用者帳號備註資訊 + * @since 2.0.0 + */ + public function getMemo(){ + return $this->queryResultArray['memo']; + } + + /** + * 修改帳號備註資訊 + * + * @param string $input 新的帳號備註資訊 + * @since 2.0.0 + */ + public function setMemo($input){ + $this->setUpdate('memo', $input); + } + + // ======================================================================== + + /** + * 取得權限清單 + * + * @return array 權限清單 + * @since 2.0.0 + */ + public function getPermissionList() { + $thisGroup = new UserGroup($this->getQueryInfo("GID")); + return $thisGroup->getPermissionList(); + } + + /** + * 是否擁有此權限 + * + * @param string $permissionName 權限名稱 + * @return bool 是否擁有 + * @throw UElearning\User\Exception\PermissionNoFoundException + * @since 2.0.0 + */ + public function havePermission($permissionName) { + $thisGroup = new UserGroup($this->getQueryInfo("GID")); + return $thisGroup->havePermission($permissionName); + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/UserAdmin.php b/htdocs/lib/User/UserAdmin.php new file mode 100644 index 0000000..1605ac7 --- /dev/null +++ b/htdocs/lib/User/UserAdmin.php @@ -0,0 +1,187 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserAdmin { + + /** + * 建立使用者 + * + * 建立使用者範例: + * + * require_once __DIR__.'/../config.php'; + * require_once UELEARNING_LIB_ROOT.'/User/UserAdmin.php'; + * use UElearning\User; + * + * try { + * $userAdmin = new User\UserAdmin(); + * $userAdmin->create( + * array( 'user_id' => 'eric', + * 'password' => 'pass123', + * 'group_id' => 'admin', + * 'enable' => true, + * 'nickname' => '艾瑞克', + * 'email' => 'eric@example.com' ) + * ); + * + * } + * // 若已有重複帳號名稱 + * catch (User\Exception\UserIdExistException $e) { + * echo 'Is exist user: ', $e->getUserId(); + * } + * + * @param array $userInfoArray 使用者資訊陣列,格式為: + * array( 'user_id' => 'root', + * 'password' => 'pass123', + * 'password_encrypt' => null, // (optional) 預設為null + * 'password_encrypted' => null, // (optional) 預設為false + * 'group_id' => 'user', + * 'class_id' => '5-2', // (optional) + * 'enable' => true, // (optional) 預設為true + * 'learnStyle_mode' => 'harf-line-learn', // (optional) + * 'material_mode' => 1, // (optional) + * 'nickname' => 'eric', // (optional) + * 'realname' => 'Eric Chiu', // (optional) + * 'email' => 'eric@example.tw', // (optional) + * 'memo' => '' ) // (optional) + * @throw UElearning\User\Exception\UserIdExistException + * @since 2.0.0 + */ + public function create($userInfoArray) { + + // 檢查必填項目有無填寫 + if(isset($userInfoArray)) { + + // 若無填寫 + if( !isset($userInfoArray['user_id']) || + !isset($userInfoArray['password']) || + !isset($userInfoArray['group_id']) ) { + throw new UElearning\Exception\NoDataException(); + } + // 若此id已存在 + else if($this->isExist($userInfoArray['user_id'])) { + throw new Exception\UserIdExistException( + $userInfoArray['user_id'] ); + } + // 沒有問題 + else { + + // 處理未帶入的資料 + if( !isset($userInfoArray['class_id']) ){ + $userInfoArray['class_id'] = null; + } + if( !isset($userInfoArray['enable']) ){ + $userInfoArray['enable'] = true; + } + if( !isset($userInfoArray['learnStyle_mode']) ){ + $userInfoArray['learnStyle_mode'] = null; + } + if( !isset($userInfoArray['material_mode']) ){ + $userInfoArray['material_mode'] = null; + } + if( !isset($userInfoArray['nickname']) ){ + $userInfoArray['nickname'] = null; + } + if( !isset($userInfoArray['realname']) ){ + $userInfoArray['realname'] = null; + } + if( !isset($userInfoArray['email']) ){ + $userInfoArray['email'] = null; + } + if( !isset($userInfoArray['memo']) ){ + $userInfoArray['memo'] = null; + } + + // 進行密碼加密 + $passUtil = new Util\Password(); + $passwdEncrypted = $passUtil->encrypt( $userInfoArray['password'] ); + + // 新增一筆使用者資料進資料庫 + $db = new Database\DBUser(); + $db->insertUser( + $userInfoArray['user_id'], + $passwdEncrypted, + $userInfoArray['group_id'], + $userInfoArray['class_id'], + $userInfoArray['enable'], + $userInfoArray['learnStyle_mode'], + $userInfoArray['material_mode'], + $userInfoArray['nickname'], + $userInfoArray['realname'], + $userInfoArray['email'], + $userInfoArray['memo'] + ); + } + } + else throw Exception\NoDataException(); + } + + /** + * 是否已有相同名稱的帳號名稱 + * + * @param string $userName 帳號名稱 + * @return bool 已有相同的帳號名稱 + * @since 2.0.0 + */ + public function isExist($userName) { + + $db = new Database\DBUser(); + $info = $db->queryUser($userName); + + if( $info != null ) return true; + else return false; + } + + /** + * 移除此使用者 + * + * 範例: + * + * try { + * $userAdmin = new User\UserAdmin(); + * $userAdmin->remove('eric'); + * } + * catch (User\Exception\UserNoFoundException $e) { + * echo 'No Found user: ', $e->getUserId(); + * } + * + * @param string $userName 帳號名稱 + * @throw UElearning\User\Exception\UserNoFoundException + * @since 2.0.0 + */ + public function remove($userName) { + + // 若有此使用者 + if($this->isExist($userName)) { + + // TODO: 檢查所有關聯的資料,確認是否可以移除 + + // 移除資料庫中的使用者 + $db = new Database\DBUser(); + $db->deleteUser($userName); + } + // 若沒有這位使用者 + else { + throw new Exception\UserNoFoundException($userName); + } + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/UserGroup.php b/htdocs/lib/User/UserGroup.php new file mode 100644 index 0000000..9a4380c --- /dev/null +++ b/htdocs/lib/User/UserGroup.php @@ -0,0 +1,234 @@ +getName(); + * $group->setName('測試用'); + * echo $group->getName(); + * } + * catch (User\Exception\GroupNoFoundException $e) { + * echo 'No Found group: '. $e->getGroupId(); + * } + * + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserGroup { + + /** + * 群組ID + * @type string + */ + protected $gId; + + // ======================================================================== + + /** + * 查詢到此帳號的所有資訊的結果 + * + * 由 $this->getQuery() 抓取資料表中所有資訊,並放在此陣列裡 + * + * @type array + */ + protected $queryResultArray; + + /** + * 從資料庫取得此群組查詢 + * + * @throw UElearning\User\Exception\GroupNoFoundException + * @since 2.0.0 + */ + protected function getQuery(){ + + // 從資料庫查詢群組 + $db = new Database\DBUser(); + $groupInfo = $db->queryGroup($this->gId); + + // 判斷有沒有這個群組 + if( $groupInfo != null ) { + $this->queryResultArray = $groupInfo; + } + else throw new Exception\GroupNoFoundException($this->gId); + } + + /** + * 從資料庫更新此群組設定 + * + * @since 2.0.0 + */ + protected function setUpdate($field, $value){ + + /// 將新設定寫進資料庫裡 + $db = new Database\DBUser(); + $db->changeGroupData($this->gId, $field, $value); + $this->getQuery(); + } + + // ======================================================================== + + /** + * 建構子 + * + * @param string $inputGID 群組ID + * @since 2.0.0 + */ + public function __construct($inputGID){ + $this->gId = $inputGID; + $this->getQuery(); + } + + // ======================================================================== + + /** + * 取得群組ID + * + * @return string 群組ID + * @since 2.0.0 + */ + public function getID(){ + return $this->gId; + } + + // ------------------------------------------------------------------------ + + /** + * 取得帳號建立時間 + * + * @return string 建立時間 + * @since 2.0.0 + */ + public function getCreateTime(){ + return $this->queryResultArray['build_time']; + } + // ======================================================================== + + /** + * 取得群組顯示名稱 + * + * @return string 群組名稱 + * @since 2.0.0 + */ + public function getName(){ + return $this->queryResultArray['name']; + } + + /** + * 設定群組顯示名稱 + * + * @param string $name 群組名稱 + * @since 2.0.0 + */ + public function setName($name){ + $this->setUpdate('name', $name); + } + + /** + * 取得帳號備註資訊 + * + * @return string 使用者帳號備註資訊 + * @since 2.0.0 + */ + public function getMemo(){ + return $this->queryResultArray['memo']; + } + + /** + * 修改帳號備註資訊 + * + * @param string $input 新的帳號備註資訊 + * @since 2.0.0 + */ + public function setMemo($input){ + $this->setUpdate('memo', $input); + } + + // ======================================================================== + + /** + * 取得權限清單 + * + * @return array 權限清單 + */ + public function getPermissionList() { + // TODO: 取得權限清單 + + } + + /** + * 是否擁有此權限 + * + * @param string $permissionName 權限名稱 + * @return bool 是否擁有 + * @throw UElearning\User\Exception\PermissionNoFoundException + * @since 2.0.0 + */ + public function havePermission($permissionName) { + switch($permissionName) { + case 'server_admin': + case 'serverAdmin': + case 'ServerAdmin': + return $this->queryResultArray['auth_admin']; + break; + + case 'client_admin': + case 'clientAdmin': + case 'ClientAdmin': + return $this->queryResultArray['auth_clientAdmin']; + break; + + default: + throw new PermissionNoFoundException('$permissionName'); + return false; + } + } + + /** + * 設定擁有此權限 + * + * @param string $permissionName 權限名稱 + * @param string $setBool 是否給予 + * @return bool 是否擁有 + * @throw UElearning\User\Exception\PermissionNoFoundException + * @since 2.0.0 + */ + public function setPermission($permissionName, $setBool) { + switch($permissionName) { + case 'server_admin': + case 'serverAdmin': + case 'ServerAdmin': + $this->setUpdate('auth_admin', $setBool); + break; + + case 'client_admin': + case 'clientAdmin': + case 'ClientAdmin': + $this->setUpdate('auth_clientAdmin', $setBool); + break; + default: + throw new PermissionNoFoundException('$permissionName'); + } + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/UserGroupAdmin.php b/htdocs/lib/User/UserGroupAdmin.php new file mode 100644 index 0000000..c443c39 --- /dev/null +++ b/htdocs/lib/User/UserGroupAdmin.php @@ -0,0 +1,151 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserGroupAdmin { + + /** + * 建立群組 + * + * 建立使用者群組範例: + * + * try { + * $groupAdmin = new User\UserGroupAdmin(); + * $groupAdmin->create( + * array( 'group_id' => 'student', + * 'name' => '學生', + * 'memo' => null, + * 'auth_server_admin' => false, + * 'auth_client_admin' => false + * )); + * + * } + * // 若已有重複群組ID + * catch (User\Exception\GroupIdExistException $e) { + * echo 'Is exist group: ', $e->getGroupId(); + * } + * + * @param array $groupArray 使用者群組資訊陣列,格式為: + * array( 'group_id' => 'student', + * 'name' => '學生', + * 'memo' => null, // (optional) 預設為null + * 'auth_server_admin' => false, // (optional) 預設為false + * 'auth_client_admin' => false ) // (optional) 預設為false + * @throw UElearning\User\Exception\GroupIdExistException + * @since 2.0.0 + */ + public function create($groupArray) { + + // 檢查有無填寫 + if(isset($groupArray)) { + + // 若必填項目無填寫 + if( !isset($groupArray['group_id']) ) { + throw new UElearning\Exception\NoDataException(); + } + // 若此id已存在 + else if( $this->isExist($groupArray['group_id']) ) { + throw new Exception\GroupIdExistException( + $groupArray['group_id'] ); + } + // 沒有問題 + else { + + // 處理未帶入的資料 + if( !isset($groupArray['name']) ){ + $groupArray['name'] = null; + } + // 處理未帶入的資料 + if( !isset($groupArray['memo']) ){ + $groupArray['memo'] = null; + } + if( !isset($groupArray['auth_server_admin']) ){ + $groupArray['auth_server_admin'] = false; + } + if( !isset($groupArray['auth_client_admin']) ){ + $groupArray['auth_client_admin'] = false; + } + + // 新增一筆使用者資料進資料庫 + $db = new Database\DBUser(); + $db->insertGroup( + $groupArray['group_id'], + $groupArray['name'], + $groupArray['memo'], + $groupArray['auth_server_admin'], + $groupArray['auth_client_admin'] + ); + } + } + else throw Exception\NoDataException(); + } + + /** + * 是否已有相同名稱的帳號名稱 + * + * @param string $group_id 群組ID + * @return bool 已有相同的群組ID + * @since 2.0.0 + */ + public function isExist($group_id) { + + $db = new Database\DBUser(); + $info = $db->queryGroup($group_id); + + if( $info != null ) return true; + else return false; + } + + /** + * 移除此群組 + * + * 範例: + * + * try { + * $groupAdmin = new User\UserGroupAdmin(); + * $groupAdmin->remove('test_student'); + * + * } + * catch (User\Exception\GroupNoFoundException $e) { + * echo 'No Found group: ', $e->getGroupId(); + * } + * + * @param string $group_id 群組ID + * @throw UElearning\User\Exception\GroupNoFoundException + * @since 2.0.0 + */ + public function remove($group_id) { + + // 若有此使用者 + if($this->isExist($group_id)) { + + // TODO: 檢查所有關聯的資料,確認是否可以移除 + + // 移除資料庫中的使用者 + $db = new Database\DBUser(); + $db->deleteGroup($group_id); + } + // 若沒有這位使用者 + else { + throw new Exception\GroupNoFoundException($group_id); + } + + } + +} \ No newline at end of file diff --git a/htdocs/lib/User/UserSession.php b/htdocs/lib/User/UserSession.php new file mode 100644 index 0000000..d4481f6 --- /dev/null +++ b/htdocs/lib/User/UserSession.php @@ -0,0 +1,288 @@ + + * @version 2.0.0 + * @package UElearning + * @subpackage User + */ +class UserSession { + + /** + * 使用者登入 + * + * 範例: + * + * require_once __DIR__.'/../config.php'; + * require_once UELEARNING_LIB_ROOT.'/User/UserSession.php'; + * use UElearning\User; + * + * try { + * $session = new User\UserSession(); + * $loginToken = $session->login('yuan', 'password', 'browser'); + * echo 'Token: '.$loginToken; + * } + * catch (User\Exception\UserNoFoundException $e) { + * echo 'No Found user: '. $e->getUserId(); + * } + * catch (User\Exception\UserPasswordErrException $e) { + * echo 'User Password wrong: '. $e->getUserId(); + * } + * catch (User\Exception\UserNoActivatedException $e) { + * echo 'User No Activiated: '. $e->getUserId(); + * } + * + * @param string $userId 帳號名稱 + * @param string $password 密碼 + * @param string $agent 用什麼裝置登入 + * @return string 登入session token + * @throw UElearning\User\Exception\UserNoFoundException + * @throw UElearning\User\Exception\UserPasswordErrException + * @throw UElearning\User\Exception\UserNoActivatedException + * @since 2.0.0 + */ + public function login($userId, $password, $agent) { + + try { + $user = new User($userId); + + // 登入密碼錯誤的話 + if( !$user->isPasswordCorrect($password) ) { + throw new Exception\UserPasswordErrException($userId); + } + // 此帳號已被停用 + else if( !$user->isEnable() ) { + throw new Exception\UserNoActivatedException($userId); + } + // 沒問題,登入此帳號 + else { + + // 使用資料庫 + $db = new Database\DBUserSession(); + + // 產生登入token + $passUtil = new Util\Password(); + $token = null; + // 防止產生出重複的token + do { + $token = $passUtil->generator(32); + } + while ($db->queryByToken($token)); + + // 登入資訊寫入資料庫 + $db->login($token, $userId, $agent); + + return $token; + } + } + // 沒有找到使用者 + catch (User\Exception\UserNoFoundException $e) { + echo 'No Found user: '. $e->getUserId(); + } + } + + // ======================================================================== + + /** + * 使用者登出 + * + * 範例: + * + * try { + * $session = new User\UserSession(); + * $session->logout('YdcfzqUuuRAR]4h6u4^Ew-qa4A-kvD5C'); + * } + * catch (User\Exception\LoginTokenNoFoundException $e) { + * echo 'No Login by token: '. $e->getToken(); + * } + * + * @param string $token 登入階段token + * @throw \UElearning\User\Exception\LoginTokenNoFoundException + * @since 2.0.0 + */ + public function logout($token) { + + $db = new Database\DBUserSession(); + + // 如果有找到此登入階段 + if( $db->queryByToken($token) ) { + $db->logout($token); + } + // 沒有此登入階段 + else { + throw new Exception\LoginTokenNoFoundException($token); + } + } + + /** + * 將其他已登入的裝置登出 + * @param string $token 登入階段token + * @return int 已登出數量 + * @throw \UElearning\User\Exception\LoginTokenNoFoundException + * @since 2.0.0 + */ + public function logoutOtherSession($token) { + + // 先從token查詢到使用者是誰 + $user_id = $this->getUserId($token); + + $db = new Database\DBUserSession(); + // 如果有找到此登入階段 + if( $db->queryByToken($token) ) { + // 查詢者個使用者的所有登入階段 + $allSession = $db->queryLoginByUserId($user_id); + + // 紀錄已登出數量 + $logoutTotal = 0; + if(isset($allSession)) { + // 將所有非此Token的裝置登出 + foreach($allSession as $key=>$thisSession) { + if($thisSession['token'] != $token) { + $this->logout($thisSession['token']); + $logoutTotal++; + } + } + }; + return $logoutTotal; + } + // 沒有此登入階段 + else { + throw new Exception\LoginTokenNoFoundException($token); + } + } + + /** + * 取得使用者物件 + * + * 範例: + * + * try { + * // 正常寫法 + * $userSession = new User\UserSession(); + * $user = $userSession->getUser(‘YZ8@(3fYb[!f!A^E4^6b4LuqxSXgZ2FJ’); + * + * // 簡短寫法(PHP 5.4以上才支援) + * //$user = (new User\UserSession())->getUser('YZ8@(3fYb[!f!A^E4^6b4LuqxSXgZ2FJ'); + * + * // 撈帳號資料 + * echo '暱稱: '.$user->getNickName(); // 取得暱稱 + * echo '本名: '.$user->getRealName(); // 取得本名 + * } + * catch (User\Exception\LoginTokenNoFoundException $e) { + * echo 'No Found Token: '. $e->getToken(); + * } + * + * @param string $token 登入階段token + * @return User 使用者物件 + * @throw \UElearning\User\Exception\LoginTokenNoFoundException + * @since 2.0.0 + */ + public function getUser($token) { + $userId = $this->getUserId($token); + return new User($userId); + } + + /** + * 取得使用者ID + * @param string $token 登入階段token + * @return string 使用者ID + * @throw \UElearning\User\Exception\LoginTokenNoFoundException + * @since 2.0.0 + */ + public function getUserId($token) { + $db = new Database\DBUserSession(); + $sessionArray = $db->queryByToken($token); + if(isset($sessionArray)) return $sessionArray['user_id']; + else throw new Exception\LoginTokenNoFoundException($token); + } + + /** + * 取得登入資訊 + * @param string $token 登入階段token + * @return Array 此登入階段資訊 + * @since 2.0.0 + */ + public function getTokenInfo($token) { + // TODO: 取得登入資訊 + } + + // ======================================================================== + + /** + * 取得所有此使用者已登入的登入階段資訊 + * @param string $userId 使用者帳號名稱 + * @return Array 已登入的所有登入階段資訊 + * @since 2.0.0 + */ + public function getUserLoginInfo($userId) { + // TODO: 取得所有此使用者已登入的登入階段資訊 + } + + /** + * 取得此使用者登入的裝置數 + * @param string $userId 使用者帳號名稱 + * @return int 所有以登入的數量 + * @since 2.0.0 + */ + public function getLoginTotalByUserId($userId) { + + // 確保若無此使用者則丟例外 + $user = new User($userId); + + // 查詢者個使用者的所有登入階段 + $db = new Database\DBUserSession(); + $allSession = $db->queryLoginByUserId($userId); + + // 回傳目前已登入的裝置數 + if(isset($allSession)) { + return count($allSession); + } + else return 0; + } + + /** + * 取得所有此使用者全部的登入階段資訊 + * + * 用於查詢登入紀錄的時候使用 + * @param string $userId 使用者帳號名稱 + * @return Array 已登入的所有登入階段資訊 + * @since 2.0.0 + */ + public function getUserAllInfo($userId) { + // TODO: 取得所有此使用者全部的登入階段資訊 + } + + /** + * 將此使用者全部登入階段登出 + * @param string $userId 使用者帳號名稱 + * @return int 已登出數量 + * @throw UElearning\User\Exception\UserNoFoundException + * @since 2.0.0 + */ + public function logoutByUser($userId) { + + // 確保若無此使用者則丟例外 + $user = new User($userId); + + // 登出此使用者所有登入階段 + $db = new Database\DBUserSession(); + + $logoutTotal = 0; + $logoutTotal = $db->logoutByUserId($userId); + return $logoutTotal; + } +} \ No newline at end of file diff --git a/htdocs/lib/Util/Password.php b/htdocs/lib/Util/Password.php new file mode 100644 index 0000000..111f108 --- /dev/null +++ b/htdocs/lib/Util/Password.php @@ -0,0 +1,160 @@ +generator(10); // 產生10個字的密碼 + * echo $passUtil->encrypt('abc'); // 加密此字串 + * + * // 核對與加密後是否吻合 + * echo $passUtil->checkSame('a9993e364706816aba3e25717850c26c9cd0d89d', 'abc'); + * + * @author Yuan Chiu + * @version 2.0.0 + * @package UElearning + * @subpackage Util + */ +class Password { + + /** + * 取得亂數字串 + * + * The MIT License + * + * Copyright (c) 2007 Tsung-Hao + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @author tsung http://plog.longwin.com.tw + * @desc http://blog.longwin.com.tw/2007/11/php_snap_image_block_2007/ + * @param int $password_len 字串長度(幾個字) + * @return string 亂數產生產生後的字串 + * + */ + public function generator($password_len){ + $password = ''; + + // remove o,0,1,l + $word = 'abcdefghijkmnpqrstuvwxyz!@#%^*()-ABCDEFGHIJKLMNPQRSTUVWXYZ;{}[]23456789'; + $len = strlen($word); + + for ($i = 0; $i < $password_len; $i++) { + $password .= $word[rand() % $len]; + } + + return $password; + } + + /** + * 加密這段字 + * + * @param string $text 原本字串 + * @return string 加密後結果字串 + * @since 2.0.0 + */ + public function encrypt($text){ + // 從config.php設定檔取得預設加密方式 + switch(ENCRYPT_MODE){ + case "MD5": + case "md5": + return $this->md5Encrypt($text); + break; + case "SHA1": + case "sha1": + return $this->sha1Encrypt($text); + break; + case "CRYPT": + case "crypt": + return $this->cryptEncrypt($text); + break; + default: + return $text; + break; + } + } + + /** + * 加密這段字 + * + * @param string $encrypted 已加密字串 + * @param string $text 原本字串 + * @return bool true代表與加密後字串一樣 + * @since 2.0.0 + */ + public function checkSame($encrypted, $text) { + // 加密此字串 + $textToEncypt = $this->encrypt($text); + + // 判斷是否吻合 + if( $textToEncypt == $encrypted ) { + return true; + } + else { + return false; + } + } + + // ------------------------------------------------------------------------ + + /** + * MD5加密這段字 + * + * @param string $text 原本字串 + * @return string 加密後結果字串 + * @since 2.0.0 + */ + public function md5Encrypt($text){ + return md5($text); + } + + /** + * SHA1加密這段字 + * + * @param string $text 原本字串 + * @return string 加密後結果字串 + * @since 2.0.0 + */ + public function sha1Encrypt($text){ + return sha1($text); + } + + /** + * CRYPT加密這段字 + * + * @param string $text 原本字串 + * @return string 加密後結果字串 + * @since 2.0.0 + */ + public function cryptEncrypt($text){ + return crypt($text); + } + +} \ No newline at end of file diff --git a/htdocs/lib_web/here b/htdocs/lib_web/here new file mode 100644 index 0000000..e69de29 diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..c6cda52 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,10 @@ + + + + + tests + tests/InstallTest.php + + + \ No newline at end of file diff --git a/sql/UElearning_2014_08_04.sql b/sql/UElearning_2014_08_04.sql new file mode 100644 index 0000000..4bed1ce --- /dev/null +++ b/sql/UElearning_2014_08_04.sql @@ -0,0 +1,244 @@ +-- phpMyAdmin SQL Dump +-- version 4.1.6 +-- http://www.phpmyadmin.net +-- +-- 主機: localhost +-- 產生時間: 2014 年 08 月 05 日 08:36 +-- 伺服器版本: 5.6.16 +-- PHP 版本: 5.5.9 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; + +-- +-- 資料庫: `UElearning` +-- + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__ABelong` +-- + +CREATE TABLE IF NOT EXISTS `chu__ABelong` ( + `TID` int(10) unsigned NOT NULL, + `AID` int(10) unsigned NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__AGroup` +-- + +CREATE TABLE IF NOT EXISTS `chu__AGroup` ( + `GID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `GName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `GMemo` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`GID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Area` +-- + +CREATE TABLE IF NOT EXISTS `chu__Area` ( + `AID` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '區域編號', + `AName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '區域名稱', + `AMapID` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '區域地圖編號', + `AIntroduction` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`AID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__CGroup` +-- + +CREATE TABLE IF NOT EXISTS `chu__CGroup` ( + `CID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `CName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `CMemo` tinytext COLLATE utf8_unicode_ci, + PRIMARY KEY (`CID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Edge` +-- + +CREATE TABLE IF NOT EXISTS `chu__Edge` ( + `Ti` int(11) NOT NULL, + `Tj` int(11) NOT NULL, + `MoveTime` int(4) NOT NULL COMMENT '移動時間(分鐘)', + `Destance` int(11) NOT NULL COMMENT '距離(M)' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__LearnActivity` +-- + +CREATE TABLE IF NOT EXISTS `chu__LearnActivity` ( + `LsID` int(10) NOT NULL, + `ThID` int(10) NOT NULL COMMENT '主題編號', + `CID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '班級名稱', + `StartTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '開始時間', + `Delay` int(11) NOT NULL COMMENT '實際狀態延誤(分)', + PRIMARY KEY (`LsID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Material` +-- + +CREATE TABLE IF NOT EXISTS `chu__Material` ( + `MID` int(10) unsigned NOT NULL COMMENT '教材內部編號', + `TID` int(10) unsigned NOT NULL COMMENT '標的內部編號', + `MMode` int(1) NOT NULL DEFAULT '0' COMMENT '教材模式', + `MUrl` varchar(1000) COLLATE utf8_unicode_ci NOT NULL COMMENT '教材檔案路徑', + PRIMARY KEY (`MID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Recommand` +-- + +CREATE TABLE IF NOT EXISTS `chu__Recommand` ( + `TID` int(3) NOT NULL COMMENT '標的內部編號', + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者帳號', + `gradation` int(11) NOT NULL COMMENT '系統推薦標地順序' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Study` +-- + +CREATE TABLE IF NOT EXISTS `chu__Study` ( + `SID` int(10) NOT NULL AUTO_INCREMENT, + `TID` int(10) NOT NULL COMMENT '標的內部編號', + `UID` int(30) NOT NULL COMMENT '使用者名稱', + `LMode` int(11) NOT NULL COMMENT '學習導引模式', + `MMode` int(11) NOT NULL COMMENT '教材模式', + `In_TargetTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '進入標的時間', + `Out_TargetTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '離開標的時間', + PRIMARY KEY (`SID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__StudyQuestion` +-- + +CREATE TABLE IF NOT EXISTS `chu__StudyQuestion` ( + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `TID` int(10) NOT NULL, + `QID` int(11) NOT NULL, + `UAns` int(11) NOT NULL, + `CAns` int(11) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Target` +-- + +CREATE TABLE IF NOT EXISTS `chu__Target` ( + `TID` int(10) unsigned NOT NULL COMMENT '標的內部編號', + `TNum` int(10) DEFAULT NULL COMMENT '標的地圖上的編號', + `TName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '標的名稱', + `TMapID` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地圖圖檔名稱', + `TLearnTime` int(4) unsigned NOT NULL COMMENT '預估此標的應該學習的時間', + `PLj` int(11) unsigned NOT NULL COMMENT '學習標的的人數限制', + `Mj` int(11) unsigned DEFAULT NULL COMMENT '目前人數', + `S` int(11) unsigned DEFAULT NULL COMMENT '學習標的飽和率上限', + `Fi` int(11) DEFAULT NULL COMMENT '學習標的滿額指標', + PRIMARY KEY (`TID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__TBelong` +-- + +CREATE TABLE IF NOT EXISTS `chu__TBelong` ( + `TID` int(10) NOT NULL, + `ThID` int(10) NOT NULL, + `Weights` int(3) NOT NULL COMMENT '當次學習主題的某一個學習標的之權重' +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__Theme` +-- + +CREATE TABLE IF NOT EXISTS `chu__Theme` ( + `ThID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ThName` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT '主題名稱', + `ThLearnTotal` int(4) NOT NULL COMMENT '學習此主題要花的總時間(m)', + `ThIntroduction` tinytext COLLATE utf8_unicode_ci COMMENT '介紹', + PRIMARY KEY (`ThID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__User` +-- + +CREATE TABLE IF NOT EXISTS `chu__User` ( + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者帳號', + `UPassword` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT '密碼', + `GID` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '使用者群組', + `CID` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用者班級', + `UEnabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '帳號啟用狀態', + `UBuild_Time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '帳號建立時間', + `LMode` enum('line-learn','harf-line-learn','non-line-learn') COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '學習導引模式', + `MMode` int(11) DEFAULT NULL COMMENT '教材模式', + `UNickname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '暱稱', + `UReal_Name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '真實姓名', + `UEmail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用者email', + `UMemo` tinytext COLLATE utf8_unicode_ci COMMENT '備註', + PRIMARY KEY (`UID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- 資料表結構 `chu__UserSession` +-- + +CREATE TABLE IF NOT EXISTS `chu__UserSession` ( + `UsID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `UToken` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '此登入階段的token', + `UID` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `UAgent` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '使用哪個裝置登入', + `ULoginDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '登入時間', + `ULogoutDate` timestamp NULL DEFAULT NULL COMMENT '登出時間', + PRIMARY KEY (`UsID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/tests/Database/DBUserTest.php b/tests/Database/DBUserTest.php new file mode 100644 index 0000000..66eee31 --- /dev/null +++ b/tests/Database/DBUserTest.php @@ -0,0 +1,216 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/Database/DBUser.php'; +require_once UELEARNING_LIB_ROOT.'/Database/Exception.php'; +use UElearning\Database\DBUser; +use UElearning\Database\Exception; + +class DBUserTest extends \PHPUnit_Framework_TestCase +{ + + protected $db; + + protected function setUp(){ + try { + // 建立資料庫管理物件 + $this->db = new DBUser(); + + } + // 若設定的DBMS不被支援 則丟出例外 + catch (Database\Exception\DatabaseNoSupportException $e) { + throw $e; + } + } + + /** + * 測試建立使用者 + * + * @dataProvider userDataProvider + */ + public function testCreateUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo){ + + $this->db->insertUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo); + } + + /** + * 測試查詢使用者 + * + * @dataProvider userDataProvider + */ + public function testQueryUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo){ + + // 查詢使用者 + $info = $this->db->queryUser($uId); + + // 比對資料是否吻合 + $this->assertEquals($info['user_id'], $uId); + $this->assertEquals($info['password'], $uPassword); + $this->assertEquals($info['group_id'], $gId); + $this->assertEquals($info['class_id'], $cId); + $this->assertEquals($info['enable'], $enable); + $this->assertEquals($info['learnStyle_mode'], $l_mode); + $this->assertEquals($info['material_mode'], $m_mode); + $this->assertEquals($info['nickname'], $nickName); + $this->assertEquals($info['realname'], $realName); + $this->assertEquals($info['email'], $email); + $this->assertEquals($info['memo'], $memo); + } + + /** + * 測試查詢所有使用者 + * + * 僅測試是否能成功執行,不驗證結果 + */ + public function testQueryAllUser(){ + + // 查詢使用者 + $infoAll = $this->db->queryAllUser(); + } + + /** + * 測試更改使用者資料 + * + * @dataProvider userDataProvider + */ + public function testChangeUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo){ + + $afterData = 'sfisjojjoij'; + + // 記下更改前的資料 + $info = $this->db->queryUser($uId); + $beforeData = $info['memo']; + + // 更改資料 + $this->db->changeUserData($uId, 'memo', $afterData); + + // 檢查更改後的結果 + $info = $this->db->queryUser($uId); + $this->assertEquals($info['memo'], $afterData); + + // 改回來 + $this->db->changeUserData($uId, 'memo', $beforeData); + + // 檢查有沒有改回來 + $info = $this->db->queryUser($uId); + $this->assertEquals($info['memo'], $beforeData); + } + + + /** + * 測試移除使用者 + * + * @dataProvider userDataProvider + */ + public function testDeleteUser($uId) { + $this->db->deleteUser($uId); + } + + /** + * 測試時要填的資料 + */ + public function userDataProvider(){ + return array( + array('yuan_unittest', 'pass123', 'admin', null, true, + 'harf-line-learn', 1, + '元兒~', 'Yuan Chiu', 'chyuaner@gmail.com', null), + + array('eee_unittest', 'qqqssss', 'admin', null, 0, + 'harf-line-learn', '1', + 'sss', 'Yuan Chiu', 'chyuanesr@gmail.com', null) + ); + } + + // ======================================================================== + + /** + * 測試建立群組 + * + * @dataProvider groupDataProvider + */ + public function testCreateGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin){ + + $this->db->insertGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin); + } + + /** + * 測試查詢群組 + * + * @dataProvider groupDataProvider + */ + public function testQueryGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin){ + // 查詢使用者 + $info = $this->db->queryGroup($gId); + + // 比對資料是否吻合 + $this->assertEquals($info['group_id'], $gId); + $this->assertEquals($info['name'], $name); + $this->assertEquals($info['memo'], $memo); + $this->assertEquals($info['auth_admin'], $auth_admin); + $this->assertEquals($info['auth_clientAdmin'], $auth_clientAdmin); + } + + /** + * 測試修改群組 + * + * @dataProvider groupDataProvider + */ + public function testChangeGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin){ + $afterData = 'sfisjojjoij'; + + // 記下更改前的資料 + $info = $this->db->queryGroup($gId); + $beforeData = $info['memo']; + + // 更改資料 + $this->db->changeGroupData($gId, 'memo', $afterData); + + // 檢查更改後的結果 + $info = $this->db->queryGroup($gId); + $this->assertEquals($info['memo'], $afterData); + + // 改回來 + $this->db->changeGroupData($gId, 'memo', $beforeData); + + // 檢查有沒有改回來 + $info = $this->db->queryGroup($gId); + $this->assertEquals($info['memo'], $beforeData); + } + + /** + * 測試移除使用者 + * + * @dataProvider groupDataProvider + */ + public function testDeleteGroup($gId) { + $this->db->deleteGroup($gId); + } + + /** + * 測試時要填的資料 + */ + public function groupDataProvider(){ + return array( + array('testG_a', '測試用群組a', null, 1, 0), + array('testG_b', '測試用群組b', 'testhahaha Groups', 0, 1) + ); + } + + // ======================================================================== + + // TODO: ClassGroup Test +} \ No newline at end of file diff --git a/tests/Database/DatabaseTest.php b/tests/Database/DatabaseTest.php new file mode 100644 index 0000000..11e54b1 --- /dev/null +++ b/tests/Database/DatabaseTest.php @@ -0,0 +1,31 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/Database/DBAdmin.php'; + +class InstallTest extends \PHPUnit_Framework_TestCase +{ + + /** + * 測試安裝初始化資料庫 + */ + public function testInstallDatabase() + { + + try { + // 建立資料庫管理物件 + $dbAdmin = new Database\DBAdmin(); + + } + // 若設定的DBMS不被支援 則丟出例外 + catch (Database\Exception\DatabaseNoSupportException $e) { + throw $e; + } + } +} \ No newline at end of file diff --git a/tests/InstallTest.php b/tests/InstallTest.php new file mode 100644 index 0000000..872d64c --- /dev/null +++ b/tests/InstallTest.php @@ -0,0 +1,33 @@ + +// */ +//namespace UElearning; +// +//require_once UELEARNING_LIB_ROOT.'/Database/DBAdmin.php'; +// +//class InstallTest extends \PHPUnit_Framework_TestCase +//{ +// +// /** +// * 測試安裝初始化資料庫 +// */ +// public function testInstallDatabase() +// { +// +// try { +// // 建立資料庫管理物件 +// $dbAdmin = new Database\DBAdmin(); +// +// // 建立所有所需的資料表 +// $dbAdmin->createAllTable(); +// } +// // 若設定的DBMS不被支援 則丟出例外 +// catch (Database\Exception\DatabaseNoSupportException $e) { +// throw $e; +// } +// } +//} \ No newline at end of file diff --git a/tests/User/ClassGroupAdminTest.php.bak b/tests/User/ClassGroupAdminTest.php.bak new file mode 100644 index 0000000..23daa9e --- /dev/null +++ b/tests/User/ClassGroupAdminTest.php.bak @@ -0,0 +1,92 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/User/ClassGroupAdmin.php'; +use UElearning\User\ClassGroupAdmin; + +class ClassGroupAdminTest extends \PHPUnit_Framework_TestCase +{ + + protected $classId; + + protected function setUp(){ + $this->classId = array(); + } + + /** + * 測試建立群組 + * + * @dataProvider groupDataProvider + */ + public function testCreateGroup($cId, $name, $memo){ + + try { + $groupAdmin = new User\ClassGroupAdmin(); + $newId = null; + $newId = $groupAdmin->create( + array( 'class_id' => $cId, + 'name' => $name, + 'memo' => $memo + )); + + array_push($this->classId, $newId); + print_r($this->classId); + } + // 若已有重複帳號名稱 + catch (User\Exception\ClassIdExistException $e) { + throw $e; + } + + } + + /** + * 測試查詢群組 + * + * @dataProvider groupDataProvider + */ + public function testCheckExist($cId){ + + if(isset($cid)) { + $groupAdmin = new User\ClassGroupAdmin(); + // 比對資料是否吻合 + $this->assertEquals($groupAdmin->isExist($cId), true); + } + } + + /** + * 測試移除使用者 + * @depends testCreateGroup + */ + public function testDeleteGroup() { + print_r($this->classId); + foreach($this->classId as $thisId) { + + try { + $groupAdmin = new User\ClassGroupAdmin(); + $groupAdmin->remove($thisId); + + $this->assertEquals($groupAdmin->isExist($thisId), false); + } + catch (User\Exception\ClassNoFoundException $e) { + throw $e; + } + } + } + + /** + * 測試時要填的資料 + */ + public function groupDataProvider(){ + return array( + array(null, '測試用群組a', null), + array(2859, '測試用群組b', 'testhahaha Groups') + ); + } + +} \ No newline at end of file diff --git a/tests/User/UserAdminTest.php b/tests/User/UserAdminTest.php new file mode 100644 index 0000000..d189a0c --- /dev/null +++ b/tests/User/UserAdminTest.php @@ -0,0 +1,100 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/User/UserAdmin.php'; +use UElearning\User\UserAdmin; + +class UserAdminTest extends \PHPUnit_Framework_TestCase +{ + + /** + * 測試建立使用者 + * + * @dataProvider userDataProvider + */ + public function testCreateUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo) + { + + try { + // 建立資料庫管理物件 + $userAdmin = new UserAdmin(); + + // TODO: 建立使用者 + $userAdmin->create( + array( 'user_id' => $uId, + 'password' => $uPassword, + 'group_id' => $gId, + 'class_id' => $cId, + 'enable' => $enable, + 'learnStyle_mode' => $l_mode, + 'material_mode' => $m_mode, + 'nickname' => $nickName, + 'realname' => $realName, + 'email' => $email, + 'memo' => $memo + )); + } + // 若設定的DBMS不被支援 則丟出例外 + catch (Database\Exception\DatabaseNoSupportException $e) { + throw $e; + } + } + + /** + * 檢查是否已確實建立 + * + * @dataProvider userDataProvider + */ + public function testCheckExist($uId) + { + // 建立資料庫管理物件 + $userAdmin = new UserAdmin(); + + // 檢查是否已確實建立 + $this->assertEquals($userAdmin->isExist($uId), true); + } + + /** + * 刪除建立的帳號(恢復原狀用) + * + * @dataProvider userDataProvider + */ + public function testDeleteUser($uId) + { + // 建立資料庫管理物件 + $userAdmin = new UserAdmin(); + + // 移除此使用者 + $userAdmin->remove($uId); + + // 檢查是否已確實建立 + $this->assertEquals($userAdmin->isExist($uId), false); + + } + + + + /** + * 測試時要填的資料 + */ + public function userDataProvider(){ + return array( + array('yuan_unittest', 'pass123', 'admin', null, true, + 'harf-line-learn', 1, + '元兒~', 'Yuan Chiu', 'chyuaner@gmail.com', null), + + array('eee_unittest', 'qqqssss', 'admin', null, 1, + 'harf-line-learn', '1', + 'sss', 'Yuan Chiu', 'chyuanesr@gmail.com', null) + ); + } + +} \ No newline at end of file diff --git a/tests/User/UserGroupAdminTest.php b/tests/User/UserGroupAdminTest.php new file mode 100644 index 0000000..0cd484c --- /dev/null +++ b/tests/User/UserGroupAdminTest.php @@ -0,0 +1,83 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/User/UserGroupAdmin.php'; +use UElearning\User\UserGroupAdmin; + +class UserGroupAdminTest extends \PHPUnit_Framework_TestCase +{ + + /** + * 測試建立群組 + * + * @dataProvider groupDataProvider + */ + public function testCreateGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin){ + + try { + $groupAdmin = new User\UserGroupAdmin(); + $groupAdmin->create( + array( 'group_id' => $gId, + 'name' => $name, + 'memo' => $memo, + 'auth_server_admin' => $auth_admin, + 'auth_client_admin' => $auth_clientAdmin + )); + + } + // 若已有重複帳號名稱 + catch (User\Exception\GroupIdExistException $e) { + throw $e; + } + + } + + /** + * 測試查詢群組 + * + * @dataProvider groupDataProvider + */ + public function testCheckExist($gId){ + + $groupAdmin = new User\UserGroupAdmin(); + + // 比對資料是否吻合 + $this->assertEquals($groupAdmin->isExist($gId), true); + } + + /** + * 測試移除使用者 + * + * @dataProvider groupDataProvider + */ + public function testDeleteGroup($gId) { + + try { + $groupAdmin = new User\UserGroupAdmin(); + $groupAdmin->remove($gId); + + $this->assertEquals($groupAdmin->isExist($gId), false); + } + catch (User\Exception\GroupNoFoundException $e) { + throw $e; + } + + } + + /** + * 測試時要填的資料 + */ + public function groupDataProvider(){ + return array( + array('testG_a', '測試用群組a', null, '1', '0'), + array('testG_b', '測試用群組b', 'testhahaha Groups', '0', '1') + ); + } + +} \ No newline at end of file diff --git a/tests/User/UserGroupTest.php b/tests/User/UserGroupTest.php new file mode 100644 index 0000000..a45c8e7 --- /dev/null +++ b/tests/User/UserGroupTest.php @@ -0,0 +1,114 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/User/UserGroup.php'; +require_once UELEARNING_LIB_ROOT.'/User/UserGroupAdmin.php'; +use UElearning\User; + +class UserGroupTest extends \PHPUnit_Framework_TestCase +{ + /** + * 測試建立群組 + * + * @dataProvider groupDataProvider + */ + public function testCreateGroup($gId, $name, $memo, $auth_admin, $auth_clientAdmin){ + + try { + $groupAdmin = new User\UserGroupAdmin(); + $groupAdmin->create( + array( 'group_id' => $gId, + 'name' => $name, + 'memo' => $memo, + 'auth_server_admin' => $auth_admin, + 'auth_client_admin' => $auth_clientAdmin + )); + + } + // 若已有重複帳號名稱 + catch (User\Exception\GroupIdExistException $e) { + throw $e; + } + + } + + /** + * 測試取得資料 + * + * @dataProvider groupDataProvider + */ + public function testGetInfo($gId, $name, $memo, $auth_admin, $auth_clientAdmin) + { + try { + $user = new User\UserGroup($gId); + + // 個人資料檢查 + $this->assertEquals($user->getName(), $name); + $this->assertEquals($user->getMemo(), $memo); + + } + catch (User\Exception\GroupNoFoundException $e) { + echo 'No Found group: '. $e->getGroupId(); + } + } + + /** + * 測試設定資料 + * + * @dataProvider groupDataProvider + */ + public function testSetInfo($gId, $name, $memo, $auth_admin, $auth_clientAdmin) + { + try { + $user = new User\UserGroup($gId); + + // 個人資料檢查 + $user->setName('叉洛伊'); + $this->assertEquals($user->getName(), '叉洛伊'); + + $user->setMemo('sacmldscmdlsvndlsknvkdsvne;vne;wnvoewzcmlsnwensc'); + $this->assertEquals($user->getMemo(), + 'sacmldscmdlsvndlsknvkdsvne;vne;wnvoewzcmlsnwensc'); + + } + catch (User\Exception\GroupNoFoundException $e) { + echo 'No Found group: '. $e->getGroupId(); + } + } + + /** + * 測試移除使用者 + * + * @dataProvider groupDataProvider + */ + public function testDeleteGroup($gId) { + + try { + $groupAdmin = new User\UserGroupAdmin(); + $groupAdmin->remove($gId); + + $this->assertEquals($groupAdmin->isExist($gId), false); + } + catch (User\Exception\GroupNoFoundException $e) { + throw $e; + } + + } + + /** + * 測試時要填的資料 + */ + public function groupDataProvider(){ + return array( + array('testG_a', '測試用群組a', null, '1', '0'), + array('testG_b', '測試用群組b', 'testhahaha Groups', '0', '1') + ); + } + +} \ No newline at end of file diff --git a/tests/User/UserTest.php b/tests/User/UserTest.php new file mode 100644 index 0000000..b4e22fd --- /dev/null +++ b/tests/User/UserTest.php @@ -0,0 +1,152 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/User/User.php'; +require_once UELEARNING_LIB_ROOT.'/User/UserAdmin.php'; +use UElearning\User; + +class UserTest extends \PHPUnit_Framework_TestCase +{ + /** + * 測試建立使用者 + * + * @dataProvider userDataProvider + */ + public function testCreateUser($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo) + { + + try { + // 建立資料庫管理物件 + $userAdmin = new User\UserAdmin(); + + // TODO: 建立使用者 + $userAdmin->create( + array( 'user_id' => $uId, + 'password' => $uPassword, + 'group_id' => $gId, + 'class_id' => $cId, + 'enable' => $enable, + 'learnStyle_mode' => $l_mode, + 'material_mode' => $m_mode, + 'nickname' => $nickName, + 'realname' => $realName, + 'email' => $email, + 'memo' => $memo + )); + } + // 若設定的DBMS不被支援 則丟出例外 + catch (Database\Exception\DatabaseNoSupportException $e) { + throw $e; + } + } + + /** + * 測試取得資料 + * + * @dataProvider userDataProvider + */ + public function testGetInfo($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo) + { + try { + $user = new User\User($uId); + + // 密碼檢查 + $this->assertEquals($user->isPasswordCorrect($uPassword), true); + $this->assertEquals($user->isPasswordCorrect($uPassword.'as1@#'), false); + + // 個人資料檢查 + $this->assertEquals($user->getNickName(), $nickName); + $this->assertEquals($user->getRealName(), $realName); + $this->assertEquals($user->getEmail(), $email); + $this->assertEquals($user->getMemo(), $memo); + + } + catch (User\Exception\UserNoFoundException $e) { + echo 'No Found user: '. $e->getUserId(); + } + } + + /** + * 測試設定資料 + * + * @dataProvider userDataProvider + */ + public function testSetInfo($uId, $uPassword, $gId, $cId, $enable, + $l_mode, $m_mode, + $nickName, $realName, $email, $memo) + { + try { + $user = new User\User($uId); + + // 密碼檢查 + $user->changePassword('asdw'); + $this->assertEquals($user->isPasswordCorrect('asdw'), true); + + // 設定啟用檢查 + $user->setEnable(false); + $this->assertEquals($user->isEnable(), false); + + // 個人資料檢查 + $user->setNickName('叉洛伊'); + $this->assertEquals($user->getNickName(), '叉洛伊'); + + $user->setRealName('Eric Chiou'); + $this->assertEquals($user->getRealName(), 'Eric Chiou'); + + $user->setEmail('sdj@example.moe'); + $this->assertEquals($user->getEmail(), 'sdj@example.moe'); + + $user->setMemo('sacmldscmdlsvndlsknvkdsvne;vne;wnvoewzcmlsnwensc'); + $this->assertEquals($user->getMemo(), + 'sacmldscmdlsvndlsknvkdsvne;vne;wnvoewzcmlsnwensc'); + + } + catch (User\Exception\UserNoFoundException $e) { + echo 'No Found user: '. $e->getUserId(); + } + } + + /** + * 刪除建立的帳號(恢復原狀用) + * + * @dataProvider userDataProvider + */ + public function testDeleteUser($uId) + { + // 建立資料庫管理物件 + $userAdmin = new User\UserAdmin(); + + // 移除此使用者 + $userAdmin->remove($uId); + + // 檢查是否已確實建立 + $this->assertEquals($userAdmin->isExist($uId), false); + + } + + /** + * 測試時要填的資料 + */ + public function userDataProvider(){ + return array( + array('yuan_unittest', 'pass123', 'admin', null, true, + 'harf-line-learn', 1, + '元兒~', 'Yuan Chiu', 'chyuaner@gmail.com', null), + + array('eee_unittest', 'qqqssss', 'admin', null, 1, + 'harf-line-learn', '1', + 'sss', 'Yuan Chiu', 'chyuanesr@gmail.com', null) + ); + } + +} \ No newline at end of file diff --git a/tests/Util/PasswordTest.php b/tests/Util/PasswordTest.php new file mode 100644 index 0000000..ad38b10 --- /dev/null +++ b/tests/Util/PasswordTest.php @@ -0,0 +1,63 @@ + + */ +namespace UElearning; + +require_once UELEARNING_LIB_ROOT.'/Util/Password.php'; +use UElearning\Util\Password; + +class PasswordTest extends \PHPUnit_Framework_TestCase +{ + + protected $passUtil; + + public function setUp(){ + // 建立密碼函式物件 + $this->passUtil = new Password(); + } + + /** + * 檢查密碼與加密後是否一樣 + * + * @dataProvider pass_dataProvider + */ + public function testCheckSame($value){ + + // 加密字串 + $encode = $this->passUtil->encrypt($value); + // 比對和加密後是否吻合 + $this->assertEquals($this->passUtil->checkSame($encode, $value), true); + } + + + /** + * 測試時要填的資料 + */ + public function pass_dataProvider(){ + + // 隨機產生測試數據 + $num = 10; // 產生幾筆測試字串 + $passUtil = new Password(); + $data_array = array(); + + for($i=0; $i<$num; $i++) { + $generator_text = $passUtil->generator(50); + array_push($data_array, array( $generator_text )); + } + + + return $data_array; + + // 固定測試字串 + /*return array( + array('123'), + array('sa'), + array('asdfmlsdm'), + array('dsamvlkscml') + );*/ + } +} \ No newline at end of file