You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helper.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @author Jakob Sack
  7. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  11. * License as published by the Free Software Foundation; either
  12. * version 3 of the License, or any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public
  20. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. */
  23. /**
  24. * Collection of useful functions
  25. */
  26. class OC_Helper {
  27. private static $mimetypes=array();
  28. private static $tmpFiles=array();
  29. /**
  30. * @brief Creates an url
  31. * @param string $app app
  32. * @param string $file file
  33. * @param array $args array with param=>value, will be appended to the returned url
  34. * The value of $args will be urlencoded
  35. * @return string the url
  36. *
  37. * Returns a url to the given app and file.
  38. */
  39. public static function linkTo( $app, $file, $args = array() ) {
  40. if( $app != '' ) {
  41. $app_path = OC_App::getAppPath($app);
  42. // Check if the app is in the app folder
  43. if( $app_path && file_exists( $app_path.'/'.$file )) {
  44. if(substr($file, -3) == 'php' || substr($file, -3) == 'css') {
  45. $urlLinkTo = OC::$WEBROOT . '/?app=' . $app;
  46. $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):'';
  47. }else{
  48. $urlLinkTo = OC_App::getAppWebPath($app) . '/' . $file;
  49. }
  50. }
  51. else{
  52. $urlLinkTo = OC::$WEBROOT . '/' . $app . '/' . $file;
  53. }
  54. }
  55. else{
  56. if( file_exists( OC::$SERVERROOT . '/core/'. $file )) {
  57. $urlLinkTo = OC::$WEBROOT . '/core/'.$file;
  58. }
  59. else{
  60. $urlLinkTo = OC::$WEBROOT . '/'.$file;
  61. }
  62. }
  63. if (!empty($args)) {
  64. $urlLinkTo .= '?';
  65. foreach($args as $k => $v) {
  66. $urlLinkTo .= '&'.$k.'='.urlencode($v);
  67. }
  68. }
  69. return $urlLinkTo;
  70. }
  71. /**
  72. * @brief Creates an absolute url
  73. * @param string $app app
  74. * @param string $file file
  75. * @param array $args array with param=>value, will be appended to the returned url
  76. * The value of $args will be urlencoded
  77. * @return string the url
  78. *
  79. * Returns a absolute url to the given app and file.
  80. */
  81. public static function linkToAbsolute( $app, $file, $args = array() ) {
  82. $urlLinkTo = self::linkTo( $app, $file, $args );
  83. return self::makeURLAbsolute($urlLinkTo);
  84. }
  85. /**
  86. * @brief Makes an $url absolute
  87. * @param string $url the url
  88. * @return string the absolute url
  89. *
  90. * Returns a absolute url to the given app and file.
  91. */
  92. public static function makeURLAbsolute( $url )
  93. {
  94. return OC_Request::serverProtocol(). '://' . OC_Request::serverHost() . $url;
  95. }
  96. /**
  97. * @brief Creates an url for remote use
  98. * @param string $service id
  99. * @return string the url
  100. *
  101. * Returns a url to the given service.
  102. */
  103. public static function linkToRemoteBase( $service ) {
  104. return self::linkTo( '', 'remote.php') . '/' . $service;
  105. }
  106. /**
  107. * @brief Creates an absolute url for remote use
  108. * @param string $service id
  109. * @return string the url
  110. *
  111. * Returns a absolute url to the given service.
  112. */
  113. public static function linkToRemote( $service, $add_slash = true ) {
  114. return self::makeURLAbsolute(self::linkToRemoteBase($service)) . (($add_slash && $service[strlen($service)-1]!='/')?'/':'');
  115. }
  116. /**
  117. * @brief Creates an absolute url for public use
  118. * @param string $service id
  119. * @return string the url
  120. *
  121. * Returns a absolute url to the given service.
  122. */
  123. public static function linkToPublic($service, $add_slash = false) {
  124. return self::linkToAbsolute( '', 'public.php') . '?service=' . $service . (($add_slash && $service[strlen($service)-1]!='/')?'/':'');
  125. }
  126. /**
  127. * @brief Creates path to an image
  128. * @param string $app app
  129. * @param string $image image name
  130. * @return string the url
  131. *
  132. * Returns the path to the image.
  133. */
  134. public static function imagePath( $app, $image ) {
  135. // Read the selected theme from the config file
  136. $theme=OC_Config::getValue( "theme" );
  137. // Check if the app is in the app folder
  138. if( file_exists( OC::$SERVERROOT."/themes/$theme/apps/$app/img/$image" )) {
  139. return OC::$WEBROOT."/themes/$theme/apps/$app/img/$image";
  140. }elseif( file_exists(OC_App::getAppPath($app)."/img/$image" )) {
  141. return OC_App::getAppWebPath($app)."/img/$image";
  142. }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/themes/$theme/$app/img/$image" )) {
  143. return OC::$WEBROOT."/themes/$theme/$app/img/$image";
  144. }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/$app/img/$image" )) {
  145. return OC::$WEBROOT."/$app/img/$image";
  146. }elseif( file_exists( OC::$SERVERROOT."/themes/$theme/core/img/$image" )) {
  147. return OC::$WEBROOT."/themes/$theme/core/img/$image";
  148. }elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )) {
  149. return OC::$WEBROOT."/core/img/$image";
  150. }else{
  151. echo('image not found: image:'.$image.' webroot:'.OC::$WEBROOT.' serverroot:'.OC::$SERVERROOT);
  152. die();
  153. }
  154. }
  155. /**
  156. * @brief get path to icon of file type
  157. * @param string $mimetype mimetype
  158. * @return string the url
  159. *
  160. * Returns the path to the image of this file type.
  161. */
  162. public static function mimetypeIcon( $mimetype ) {
  163. $alias=array('application/xml'=>'code/xml');
  164. if(isset($alias[$mimetype])) {
  165. $mimetype=$alias[$mimetype];
  166. }
  167. // Replace slash with a minus
  168. $mimetype = str_replace( "/", "-", $mimetype );
  169. // Is it a dir?
  170. if( $mimetype == "dir" ) {
  171. return OC::$WEBROOT."/core/img/filetypes/folder.png";
  172. }
  173. // Icon exists?
  174. if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
  175. return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
  176. }
  177. //try only the first part of the filetype
  178. $mimetype=substr($mimetype,0,strpos($mimetype,'-'));
  179. if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
  180. return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
  181. }
  182. else{
  183. return OC::$WEBROOT."/core/img/filetypes/file.png";
  184. }
  185. }
  186. /**
  187. * @brief Make a human file size
  188. * @param int $bytes file size in bytes
  189. * @return string a human readable file size
  190. *
  191. * Makes 2048 to 2 kB.
  192. */
  193. public static function humanFileSize( $bytes ) {
  194. if( $bytes < 1024 ) {
  195. return "$bytes B";
  196. }
  197. $bytes = round( $bytes / 1024, 1 );
  198. if( $bytes < 1024 ) {
  199. return "$bytes kB";
  200. }
  201. $bytes = round( $bytes / 1024, 1 );
  202. if( $bytes < 1024 ) {
  203. return "$bytes MB";
  204. }
  205. // Wow, heavy duty for owncloud
  206. $bytes = round( $bytes / 1024, 1 );
  207. return "$bytes GB";
  208. }
  209. /**
  210. * @brief Make a computer file size
  211. * @param string $str file size in a fancy format
  212. * @return int a file size in bytes
  213. *
  214. * Makes 2kB to 2048.
  215. *
  216. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  217. */
  218. public static function computerFileSize( $str ) {
  219. $str=strtolower($str);
  220. $bytes_array = array(
  221. 'b' => 1,
  222. 'k' => 1024,
  223. 'kb' => 1024,
  224. 'mb' => 1024 * 1024,
  225. 'm' => 1024 * 1024,
  226. 'gb' => 1024 * 1024 * 1024,
  227. 'g' => 1024 * 1024 * 1024,
  228. 'tb' => 1024 * 1024 * 1024 * 1024,
  229. 't' => 1024 * 1024 * 1024 * 1024,
  230. 'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
  231. 'p' => 1024 * 1024 * 1024 * 1024 * 1024,
  232. );
  233. $bytes = floatval($str);
  234. if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  235. $bytes *= $bytes_array[$matches[1]];
  236. }
  237. $bytes = round($bytes, 2);
  238. return $bytes;
  239. }
  240. /**
  241. * @brief Recursive editing of file permissions
  242. * @param string $path path to file or folder
  243. * @param int $filemode unix style file permissions
  244. * @return bool
  245. */
  246. static function chmodr($path, $filemode) {
  247. if (!is_dir($path))
  248. return chmod($path, $filemode);
  249. $dh = opendir($path);
  250. while (($file = readdir($dh)) !== false) {
  251. if($file != '.' && $file != '..') {
  252. $fullpath = $path.'/'.$file;
  253. if(is_link($fullpath))
  254. return false;
  255. elseif(!is_dir($fullpath) && !@chmod($fullpath, $filemode))
  256. return false;
  257. elseif(!self::chmodr($fullpath, $filemode))
  258. return false;
  259. }
  260. }
  261. closedir($dh);
  262. if(@chmod($path, $filemode))
  263. return true;
  264. else
  265. return false;
  266. }
  267. /**
  268. * @brief Recursive copying of folders
  269. * @param string $src source folder
  270. * @param string $dest target folder
  271. *
  272. */
  273. static function copyr($src, $dest) {
  274. if(is_dir($src)) {
  275. if(!is_dir($dest)) {
  276. mkdir($dest);
  277. }
  278. $files = scandir($src);
  279. foreach ($files as $file) {
  280. if ($file != "." && $file != "..") {
  281. self::copyr("$src/$file", "$dest/$file");
  282. }
  283. }
  284. }elseif(file_exists($src)) {
  285. copy($src, $dest);
  286. }
  287. }
  288. /**
  289. * @brief Recursive deletion of folders
  290. * @param string $dir path to the folder
  291. * @return bool
  292. */
  293. static function rmdirr($dir) {
  294. if(is_dir($dir)) {
  295. $files=scandir($dir);
  296. foreach($files as $file) {
  297. if ($file != "." && $file != "..") {
  298. self::rmdirr("$dir/$file");
  299. }
  300. }
  301. rmdir($dir);
  302. }elseif(file_exists($dir)) {
  303. unlink($dir);
  304. }
  305. if(file_exists($dir)) {
  306. return false;
  307. }else{
  308. return true;
  309. }
  310. }
  311. /**
  312. * get the mimetype form a local file
  313. * @param string $path
  314. * @return string
  315. * does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
  316. */
  317. static function getMimeType($path) {
  318. $isWrapped=(strpos($path,'://')!==false) and (substr($path,0,7)=='file://');
  319. if (@is_dir($path)) {
  320. // directories are easy
  321. return "httpd/unix-directory";
  322. }
  323. if(strpos($path,'.')) {
  324. //try to guess the type by the file extension
  325. if(!self::$mimetypes || self::$mimetypes != include 'mimetypes.list.php') {
  326. self::$mimetypes=include 'mimetypes.list.php';
  327. }
  328. $extension=strtolower(strrchr(basename($path), "."));
  329. $extension=substr($extension,1);//remove leading .
  330. $mimeType=(isset(self::$mimetypes[$extension]))?self::$mimetypes[$extension]:'application/octet-stream';
  331. }else{
  332. $mimeType='application/octet-stream';
  333. }
  334. if($mimeType=='application/octet-stream' and function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)) {
  335. $info = @strtolower(finfo_file($finfo,$path));
  336. if($info) {
  337. $mimeType=substr($info,0,strpos($info,';'));
  338. }
  339. finfo_close($finfo);
  340. }
  341. if (!$isWrapped and $mimeType=='application/octet-stream' && function_exists("mime_content_type")) {
  342. // use mime magic extension if available
  343. $mimeType = mime_content_type($path);
  344. }
  345. if (!$isWrapped and $mimeType=='application/octet-stream' && OC_Helper::canExecute("file")) {
  346. // it looks like we have a 'file' command,
  347. // lets see it it does have mime support
  348. $path=escapeshellarg($path);
  349. $fp = popen("file -i -b $path 2>/dev/null", "r");
  350. $reply = fgets($fp);
  351. pclose($fp);
  352. //trim the character set from the end of the response
  353. $mimeType=substr($reply,0,strrpos($reply,' '));
  354. $mimeType=substr($mimeType,0,strrpos($mimeType,"\n"));
  355. //trim ;
  356. if (strpos($mimeType, ';') !== false) {
  357. $mimeType = strstr($mimeType, ';', true);
  358. }
  359. }
  360. return $mimeType;
  361. }
  362. /**
  363. * get the mimetype form a data string
  364. * @param string $data
  365. * @return string
  366. */
  367. static function getStringMimeType($data) {
  368. if(function_exists('finfo_open') and function_exists('finfo_file')) {
  369. $finfo=finfo_open(FILEINFO_MIME);
  370. return finfo_buffer($finfo, $data);
  371. }else{
  372. $tmpFile=OC_Helper::tmpFile();
  373. $fh=fopen($tmpFile,'wb');
  374. fwrite($fh,$data,8024);
  375. fclose($fh);
  376. $mime=self::getMimeType($tmpFile);
  377. unset($tmpFile);
  378. return $mime;
  379. }
  380. }
  381. /**
  382. * @brief Checks $_REQUEST contains a var for the $s key. If so, returns the html-escaped value of this var; otherwise returns the default value provided by $d.
  383. * @param string $s name of the var to escape, if set.
  384. * @param string $d default value.
  385. * @return string the print-safe value.
  386. *
  387. */
  388. //FIXME: should also check for value validation (i.e. the email is an email).
  389. public static function init_var($s, $d="") {
  390. $r = $d;
  391. if(isset($_REQUEST[$s]) && !empty($_REQUEST[$s]))
  392. $r = stripslashes(htmlspecialchars($_REQUEST[$s]));
  393. return $r;
  394. }
  395. /**
  396. * returns "checked"-attribute if request contains selected radio element OR if radio element is the default one -- maybe?
  397. * @param string $s Name of radio-button element name
  398. * @param string $v Value of current radio-button element
  399. * @param string $d Value of default radio-button element
  400. */
  401. public static function init_radio($s, $v, $d) {
  402. if((isset($_REQUEST[$s]) && $_REQUEST[$s]==$v) || (!isset($_REQUEST[$s]) && $v == $d))
  403. print "checked=\"checked\" ";
  404. }
  405. /**
  406. * detect if a given program is found in the search PATH
  407. *
  408. * @param string $program name
  409. * @param string $optional search path, defaults to $PATH
  410. * @return bool true if executable program found in path
  411. */
  412. public static function canExecute($name, $path = false) {
  413. // path defaults to PATH from environment if not set
  414. if ($path === false) {
  415. $path = getenv("PATH");
  416. }
  417. // check method depends on operating system
  418. if (!strncmp(PHP_OS, "WIN", 3)) {
  419. // on Windows an appropriate COM or EXE file needs to exist
  420. $exts = array(".exe", ".com");
  421. $check_fn = "file_exists";
  422. } else {
  423. // anywhere else we look for an executable file of that name
  424. $exts = array("");
  425. $check_fn = "is_executable";
  426. }
  427. // Default check will be done with $path directories :
  428. $dirs = explode(PATH_SEPARATOR, $path);
  429. // WARNING : We have to check if open_basedir is enabled :
  430. $obd = ini_get('open_basedir');
  431. if($obd != "none"){
  432. $obd_values = explode(PATH_SEPARATOR, $obd);
  433. if(count($obd_values) > 0 and $obd_values[0]){
  434. // open_basedir is in effect !
  435. // We need to check if the program is in one of these dirs :
  436. $dirs = $obd_values;
  437. }
  438. }
  439. foreach($dirs as $dir){
  440. foreach($exts as $ext){
  441. if($check_fn("$dir/$name".$ext))
  442. return true;
  443. }
  444. }
  445. return false;
  446. }
  447. /**
  448. * copy the contents of one stream to another
  449. * @param resource $source
  450. * @param resource $target
  451. * @return int the number of bytes copied
  452. */
  453. public static function streamCopy($source,$target) {
  454. if(!$source or !$target) {
  455. return false;
  456. }
  457. $count=0;
  458. while(!feof($source)) {
  459. $count+=fwrite($target,fread($source,8192));
  460. }
  461. return $count;
  462. }
  463. /**
  464. * create a temporary file with an unique filename
  465. * @param string $postfix
  466. * @return string
  467. *
  468. * temporary files are automatically cleaned up after the script is finished
  469. */
  470. public static function tmpFile($postfix='') {
  471. $file=get_temp_dir().'/'.md5(time().rand()).$postfix;
  472. $fh=fopen($file,'w');
  473. fclose($fh);
  474. self::$tmpFiles[]=$file;
  475. return $file;
  476. }
  477. /**
  478. * create a temporary folder with an unique filename
  479. * @return string
  480. *
  481. * temporary files are automatically cleaned up after the script is finished
  482. */
  483. public static function tmpFolder() {
  484. $path=get_temp_dir().'/'.md5(time().rand());
  485. mkdir($path);
  486. self::$tmpFiles[]=$path;
  487. return $path.'/';
  488. }
  489. /**
  490. * remove all files created by self::tmpFile
  491. */
  492. public static function cleanTmp() {
  493. $leftoversFile=get_temp_dir().'/oc-not-deleted';
  494. if(file_exists($leftoversFile)) {
  495. $leftovers=file($leftoversFile);
  496. foreach($leftovers as $file) {
  497. self::rmdirr($file);
  498. }
  499. unlink($leftoversFile);
  500. }
  501. foreach(self::$tmpFiles as $file) {
  502. if(file_exists($file)) {
  503. if(!self::rmdirr($file)) {
  504. file_put_contents($leftoversFile, $file."\n", FILE_APPEND);
  505. }
  506. }
  507. }
  508. }
  509. /**
  510. * Adds a suffix to the name in case the file exists
  511. *
  512. * @param $path
  513. * @param $filename
  514. * @return string
  515. */
  516. public static function buildNotExistingFileName($path, $filename) {
  517. if($path==='/') {
  518. $path='';
  519. }
  520. if ($pos = strrpos($filename, '.')) {
  521. $name = substr($filename, 0, $pos);
  522. $ext = substr($filename, $pos);
  523. } else {
  524. $name = $filename;
  525. $ext = '';
  526. }
  527. $newpath = $path . '/' . $filename;
  528. $counter = 2;
  529. while (OC_Filesystem::file_exists($newpath)) {
  530. $newname = $name . ' (' . $counter . ')' . $ext;
  531. $newpath = $path . '/' . $newname;
  532. $counter++;
  533. }
  534. return $newpath;
  535. }
  536. /*
  537. * checks if $sub is a subdirectory of $parent
  538. *
  539. * @param string $sub
  540. * @param string $parent
  541. * @return bool
  542. */
  543. public static function issubdirectory($sub, $parent) {
  544. if($sub == null || $sub == '' || $parent == null || $parent == '') {
  545. return false;
  546. }
  547. $realpath_sub = realpath($sub);
  548. $realpath_parent = realpath($parent);
  549. if(($realpath_sub == false && substr_count($realpath_sub, './') != 0) || ($realpath_parent == false && substr_count($realpath_parent, './') != 0)) { //it checks for both ./ and ../
  550. return false;
  551. }
  552. if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != '') {
  553. if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent) {
  554. return true;
  555. }
  556. }else{
  557. if(substr($sub, 0, strlen($parent)) == $parent) {
  558. return true;
  559. }
  560. }
  561. /*echo 'SUB: ' . $sub . "\n";
  562. echo 'PAR: ' . $parent . "\n";
  563. echo 'REALSUB: ' . $realpath_sub . "\n";
  564. echo 'REALPAR: ' . $realpath_parent . "\n";
  565. echo substr($realpath_sub, 0, strlen($realpath_parent));
  566. exit;*/
  567. return false;
  568. }
  569. /**
  570. * @brief Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  571. *
  572. * @param array $input The array to work on
  573. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  574. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  575. * @return array
  576. *
  577. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  578. * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
  579. *
  580. */
  581. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  582. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  583. $ret = array();
  584. foreach ($input as $k => $v) {
  585. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  586. }
  587. return $ret;
  588. }
  589. /**
  590. * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
  591. *
  592. * @param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
  593. * @param string $replacement The replacement string.
  594. * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
  595. * @param int $length Length of the part to be replaced
  596. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  597. * @return string
  598. *
  599. */
  600. public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
  601. $start = intval($start);
  602. $length = intval($length);
  603. $string = mb_substr($string, 0, $start, $encoding) .
  604. $replacement .
  605. mb_substr($string, $start+$length, mb_strlen($string, 'UTF-8')-$start, $encoding);
  606. return $string;
  607. }
  608. /**
  609. * @brief Replace all occurrences of the search string with the replacement string
  610. *
  611. * @param string $search The value being searched for, otherwise known as the needle.
  612. * @param string $replace The replacement
  613. * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
  614. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  615. * @param int $count If passed, this will be set to the number of replacements performed.
  616. * @return string
  617. *
  618. */
  619. public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
  620. $offset = -1;
  621. $length = mb_strlen($search, $encoding);
  622. while(($i = mb_strrpos($subject, $search, $offset, $encoding)) !== false ) {
  623. $subject = OC_Helper::mb_substr_replace($subject, $replace, $i, $length);
  624. $offset = $i - mb_strlen($subject, $encoding);
  625. $count++;
  626. }
  627. return $subject;
  628. }
  629. /**
  630. * @brief performs a search in a nested array
  631. * @param array $haystack the array to be searched
  632. * @param string $needle the search string
  633. * @param string $index optional, only search this key name
  634. * @return mixed the key of the matching field, otherwise false
  635. *
  636. * performs a search in a nested array
  637. *
  638. * taken from http://www.php.net/manual/en/function.array-search.php#97645
  639. */
  640. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  641. $aIt = new RecursiveArrayIterator($haystack);
  642. $it = new RecursiveIteratorIterator($aIt);
  643. while($it->valid()) {
  644. if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
  645. return $aIt->key();
  646. }
  647. $it->next();
  648. }
  649. return false;
  650. }
  651. }