util.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. /**
  3. * Class for utility functions
  4. *
  5. */
  6. class OC_Util {
  7. public static $scripts=array();
  8. public static $styles=array();
  9. public static $headers=array();
  10. private static $rootMounted=false;
  11. private static $fsSetup=false;
  12. public static $core_styles=array();
  13. public static $core_scripts=array();
  14. // Can be set up
  15. public static function setupFS( $user = '' ){// configure the initial filesystem based on the configuration
  16. if(self::$fsSetup){//setting up the filesystem twice can only lead to trouble
  17. return false;
  18. }
  19. $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  20. //first set up the local "root" storage
  21. if(!self::$rootMounted){
  22. OC_Filesystem::mount('OC_Filestorage_Local',array('datadir'=>$CONFIG_DATADIRECTORY),'/');
  23. self::$rootMounted=true;
  24. }
  25. // If we are not forced to load a specific user we load the one that is logged in
  26. if( $user == "" && OC_User::isLoggedIn()){
  27. $user = OC_User::getUser();
  28. }
  29. if( $user != "" ){ //if we aren't logged in, there is no use to set up the filesystem
  30. $user_dir = '/'.$user.'/files';
  31. $userdirectory = $CONFIG_DATADIRECTORY.$user_dir;
  32. if( !is_dir( $userdirectory )){
  33. mkdir( $userdirectory, 0755, true );
  34. }
  35. //jail the user into his "home" directory
  36. OC_Filesystem::init($user_dir);
  37. $quotaProxy=new OC_FileProxy_Quota();
  38. OC_FileProxy::register($quotaProxy);
  39. self::$fsSetup=true;
  40. // Load personal mount config
  41. if (is_file($CONFIG_DATADIRECTORY.'/'.$user.'/mount.php')) {
  42. $mountConfig = include($CONFIG_DATADIRECTORY.'/'.$user.'/mount.php');
  43. if (isset($mountConfig['user'][$user])) {
  44. foreach ($mountConfig['user'][$user] as $mountPoint => $options) {
  45. OC_Filesystem::mount($options['class'], $options['options'], $mountPoint);
  46. }
  47. }
  48. }
  49. OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir));
  50. }
  51. }
  52. public static function tearDownFS(){
  53. OC_Filesystem::tearDown();
  54. self::$fsSetup=false;
  55. }
  56. /**
  57. * get the current installed version of ownCloud
  58. * @return array
  59. */
  60. public static function getVersion(){
  61. return array(4,80,1);
  62. }
  63. /**
  64. * get the current installed version string of ownCloud
  65. * @return string
  66. */
  67. public static function getVersionString(){
  68. return '5 pre alpha';
  69. }
  70. /**
  71. * get the current installed edition of ownCloud. There is the community edition that just returns an empty string and the enterprise edition that returns "Enterprise".
  72. * @return string
  73. */
  74. public static function getEditionString(){
  75. return '';
  76. }
  77. /**
  78. * add a javascript file
  79. *
  80. * @param appid $application
  81. * @param filename $file
  82. */
  83. public static function addScript( $application, $file = null ){
  84. if( is_null( $file )){
  85. $file = $application;
  86. $application = "";
  87. }
  88. if( !empty( $application )){
  89. self::$scripts[] = "$application/js/$file";
  90. }else{
  91. self::$scripts[] = "js/$file";
  92. }
  93. }
  94. /**
  95. * add a css file
  96. *
  97. * @param appid $application
  98. * @param filename $file
  99. */
  100. public static function addStyle( $application, $file = null ){
  101. if( is_null( $file )){
  102. $file = $application;
  103. $application = "";
  104. }
  105. if( !empty( $application )){
  106. self::$styles[] = "$application/css/$file";
  107. }else{
  108. self::$styles[] = "css/$file";
  109. }
  110. }
  111. /**
  112. * @brief Add a custom element to the header
  113. * @param string tag tag name of the element
  114. * @param array $attributes array of attributes for the element
  115. * @param string $text the text content for the element
  116. */
  117. public static function addHeader( $tag, $attributes, $text=''){
  118. self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text);
  119. }
  120. /**
  121. * formats a timestamp in the "right" way
  122. *
  123. * @param int timestamp $timestamp
  124. * @param bool dateOnly option to ommit time from the result
  125. */
  126. public static function formatDate( $timestamp,$dateOnly=false){
  127. if(isset($_SESSION['timezone'])){//adjust to clients timezone if we know it
  128. $systemTimeZone = intval(date('O'));
  129. $systemTimeZone=(round($systemTimeZone/100,0)*60)+($systemTimeZone%100);
  130. $clientTimeZone=$_SESSION['timezone']*60;
  131. $offset=$clientTimeZone-$systemTimeZone;
  132. $timestamp=$timestamp+$offset*60;
  133. }
  134. $timeformat=$dateOnly?'F j, Y':'F j, Y, H:i';
  135. return date($timeformat,$timestamp);
  136. }
  137. /**
  138. * Shows a pagenavi widget where you can jump to different pages.
  139. *
  140. * @param int $pagecount
  141. * @param int $page
  142. * @param string $url
  143. * @return OC_Template
  144. */
  145. public static function getPageNavi($pagecount,$page,$url) {
  146. $pagelinkcount=8;
  147. if ($pagecount>1) {
  148. $pagestart=$page-$pagelinkcount;
  149. if($pagestart<0) $pagestart=0;
  150. $pagestop=$page+$pagelinkcount;
  151. if($pagestop>$pagecount) $pagestop=$pagecount;
  152. $tmpl = new OC_Template( '', 'part.pagenavi', '' );
  153. $tmpl->assign('page',$page);
  154. $tmpl->assign('pagecount',$pagecount);
  155. $tmpl->assign('pagestart',$pagestart);
  156. $tmpl->assign('pagestop',$pagestop);
  157. $tmpl->assign('url',$url);
  158. return $tmpl;
  159. }
  160. }
  161. /**
  162. * check if the current server configuration is suitable for ownCloud
  163. * @return array arrays with error messages and hints
  164. */
  165. public static function checkServer(){
  166. $errors=array();
  167. //check for database drivers
  168. if(!(is_callable('sqlite_open') or class_exists('SQLite3')) and !is_callable('mysql_connect') and !is_callable('pg_connect')){
  169. $errors[]=array('error'=>'No database drivers (sqlite, mysql, or postgresql) installed.<br/>','hint'=>'');//TODO: sane hint
  170. }
  171. $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
  172. $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
  173. //common hint for all file permissons error messages
  174. $permissionsHint="Permissions can usually be fixed by giving the webserver write access to the ownCloud directory";
  175. // Check if config folder is writable.
  176. if(!is_writable(OC::$SERVERROOT."/config/")) {
  177. $errors[]=array('error'=>"Can't write into config directory 'config'",'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud");
  178. }
  179. // Check if apps folder is writable.
  180. if(OC_Config::getValue('writable_appsdir', true) && !is_writable(OC::$SERVERROOT."/apps/")) {
  181. $errors[]=array('error'=>"Can't write into apps directory 'apps'",'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud");
  182. }
  183. $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
  184. //check for correct file permissions
  185. if(!stristr(PHP_OS, 'WIN')){
  186. $permissionsModHint="Please change the permissions to 0770 so that the directory cannot be listed by other users.";
  187. $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)),-3);
  188. if(substr($prems,-1)!='0'){
  189. OC_Helper::chmodr($CONFIG_DATADIRECTORY,0770);
  190. clearstatcache();
  191. $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)),-3);
  192. if(substr($prems,2,1)!='0'){
  193. $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') is readable for other users<br/>','hint'=>$permissionsModHint);
  194. }
  195. }
  196. if( OC_Config::getValue( "enablebackup", false )){
  197. $CONFIG_BACKUPDIRECTORY = OC_Config::getValue( "backupdirectory", OC::$SERVERROOT."/backup" );
  198. $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)),-3);
  199. if(substr($prems,-1)!='0'){
  200. OC_Helper::chmodr($CONFIG_BACKUPDIRECTORY,0770);
  201. clearstatcache();
  202. $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)),-3);
  203. if(substr($prems,2,1)!='0'){
  204. $errors[]=array('error'=>'Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable for other users<br/>','hint'=>$permissionsModHint);
  205. }
  206. }
  207. }
  208. }else{
  209. //TODO: permissions checks for windows hosts
  210. }
  211. // Create root dir.
  212. if(!is_dir($CONFIG_DATADIRECTORY)){
  213. $success=@mkdir($CONFIG_DATADIRECTORY);
  214. if(!$success) {
  215. $errors[]=array('error'=>"Can't create data directory (".$CONFIG_DATADIRECTORY.")",'hint'=>"You can usually fix this by giving the webserver write access to the ownCloud directory '".OC::$SERVERROOT."' (in a terminal, use the command 'chown -R www-data:www-data /path/to/your/owncloud/install/data' ");
  216. }
  217. } else if(!is_writable($CONFIG_DATADIRECTORY)){
  218. $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud<br/>','hint'=>$permissionsHint);
  219. }
  220. // check if all required php modules are present
  221. if(!class_exists('ZipArchive')){
  222. $errors[]=array('error'=>'PHP module zip not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  223. }
  224. if(!function_exists('mb_detect_encoding')){
  225. $errors[]=array('error'=>'PHP module mb multibyte not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  226. }
  227. if(!function_exists('ctype_digit')){
  228. $errors[]=array('error'=>'PHP module ctype is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  229. }
  230. if(!function_exists('json_encode')){
  231. $errors[]=array('error'=>'PHP module JSON is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  232. }
  233. if(!function_exists('imagepng')){
  234. $errors[]=array('error'=>'PHP module GD is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  235. }
  236. if(floatval(phpversion())<5.3){
  237. $errors[]=array('error'=>'PHP 5.3 is required.<br/>','hint'=>'Please ask your server administrator to update PHP to version 5.3 or higher. PHP 5.2 is no longer supported by ownCloud and the PHP community.');
  238. }
  239. if(!defined('PDO::ATTR_DRIVER_NAME')){
  240. $errors[]=array('error'=>'PHP PDO module is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.');
  241. }
  242. return $errors;
  243. }
  244. public static function displayLoginPage($parameters = array()){
  245. if(isset($_COOKIE["username"])){
  246. $parameters["username"] = $_COOKIE["username"];
  247. } else {
  248. $parameters["username"] = '';
  249. }
  250. $sectoken=rand(1000000,9999999);
  251. $_SESSION['sectoken']=$sectoken;
  252. $parameters["sectoken"] = $sectoken;
  253. OC_Template::printGuestPage("", "login", $parameters);
  254. }
  255. /**
  256. * Check if the app is enabled, redirects to home if not
  257. */
  258. public static function checkAppEnabled($app){
  259. if( !OC_App::isEnabled($app)){
  260. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  261. exit();
  262. }
  263. }
  264. /**
  265. * Check if the user is logged in, redirects to home if not. With
  266. * redirect URL parameter to the request URI.
  267. */
  268. public static function checkLoggedIn(){
  269. // Check if we are a user
  270. if( !OC_User::isLoggedIn()){
  271. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ).'?redirect_url='.urlencode($_SERVER["REQUEST_URI"]));
  272. exit();
  273. }
  274. }
  275. /**
  276. * Check if the user is a admin, redirects to home if not
  277. */
  278. public static function checkAdminUser(){
  279. // Check if we are a user
  280. self::checkLoggedIn();
  281. if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){
  282. header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
  283. exit();
  284. }
  285. }
  286. /**
  287. * Redirect to the user default page
  288. */
  289. public static function redirectToDefaultPage(){
  290. OC_Log::write('core','redirectToDefaultPage',OC_Log::DEBUG);
  291. if(isset($_REQUEST['redirect_url']) && (substr($_REQUEST['redirect_url'], 0, strlen(OC::$WEBROOT)) == OC::$WEBROOT || $_REQUEST['redirect_url'][0] == '/')) {
  292. header( 'Location: '.$_REQUEST['redirect_url']);
  293. }
  294. else if (isset(OC::$REQUESTEDAPP) && !empty(OC::$REQUESTEDAPP)) {
  295. header( 'Location: '.OC::$WEBROOT.'/?app='.OC::$REQUESTEDAPP );
  296. }
  297. else {
  298. header( 'Location: '.OC::$WEBROOT.'/'.OC_Appconfig::getValue('core', 'defaultpage', '?app=files'));
  299. }
  300. exit();
  301. }
  302. /**
  303. * get an id unqiue for this instance
  304. * @return string
  305. */
  306. public static function getInstanceId(){
  307. $id=OC_Config::getValue('instanceid',null);
  308. if(is_null($id)){
  309. $id=uniqid();
  310. OC_Config::setValue('instanceid',$id);
  311. }
  312. return $id;
  313. }
  314. /**
  315. * @brief Register an get/post call. This is important to prevent CSRF attacks
  316. * Todo: Write howto
  317. * @return $token Generated token.
  318. */
  319. public static function callRegister(){
  320. //mamimum time before token exires
  321. $maxtime=(60*60); // 1 hour
  322. // generate a random token.
  323. $token=mt_rand(1000,9000).mt_rand(1000,9000).mt_rand(1000,9000);
  324. // store the token together with a timestamp in the session.
  325. $_SESSION['requesttoken-'.$token]=time();
  326. // cleanup old tokens garbage collector
  327. // only run every 20th time so we don't waste cpu cycles
  328. if(rand(0,20)==0) {
  329. foreach($_SESSION as $key=>$value) {
  330. // search all tokens in the session
  331. if(substr($key,0,12)=='requesttoken') {
  332. if($value+$maxtime<time()){
  333. // remove outdated tokens
  334. unset($_SESSION[$key]);
  335. }
  336. }
  337. }
  338. }
  339. // return the token
  340. return($token);
  341. }
  342. /**
  343. * @brief Check an ajax get/post call if the request token is valid.
  344. * @return boolean False if request token is not set or is invalid.
  345. */
  346. public static function isCallRegistered(){
  347. //mamimum time before token exires
  348. $maxtime=(60*60); // 1 hour
  349. if(isset($_GET['requesttoken'])) {
  350. $token=$_GET['requesttoken'];
  351. }elseif(isset($_POST['requesttoken'])){
  352. $token=$_POST['requesttoken'];
  353. }elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])){
  354. $token=$_SERVER['HTTP_REQUESTTOKEN'];
  355. }else{
  356. //no token found.
  357. return false;
  358. }
  359. if(isset($_SESSION['requesttoken-'.$token])) {
  360. $timestamp=$_SESSION['requesttoken-'.$token];
  361. if($timestamp+$maxtime<time()){
  362. return false;
  363. }else{
  364. //token valid
  365. return true;
  366. }
  367. }else{
  368. return false;
  369. }
  370. }
  371. /**
  372. * @brief Check an ajax get/post call if the request token is valid. exit if not.
  373. * Todo: Write howto
  374. */
  375. public static function callCheck(){
  376. if(!OC_Util::isCallRegistered()) {
  377. exit;
  378. }
  379. }
  380. /**
  381. * @brief Public function to sanitize HTML
  382. *
  383. * This function is used to sanitize HTML and should be applied on any string or array of strings before displaying it on a web page.
  384. *
  385. * @param string or array of strings
  386. * @return array with sanitized strings or a single sinitized string, depends on the input parameter.
  387. */
  388. public static function sanitizeHTML( &$value ){
  389. if (is_array($value) || is_object($value)) array_walk_recursive($value,'OC_Util::sanitizeHTML');
  390. else $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
  391. return $value;
  392. }
  393. }