PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/revslider/inc_php/framework/functions.class.php

https://github.com/alniko009/magic
PHP | 776 lines | 591 code | 84 blank | 101 comment | 64 complexity | 657c87eb3068d2fecd770362d64f0896 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. class UniteFunctionsRev{
  3. public static function throwError($message,$code=null){
  4. if(!empty($code))
  5. throw new Exception($message,$code);
  6. else
  7. throw new Exception($message);
  8. }
  9. /**
  10. *
  11. * set output for download
  12. */
  13. public static function downloadFile($str,$filename="output.txt"){
  14. //output for download
  15. header('Content-Description: File Transfer');
  16. header('Content-Type: text/html; charset=UTF-8');
  17. header("Content-Disposition: attachment; filename=".$filename.";");
  18. header("Content-Transfer-Encoding: binary");
  19. header("Content-Length: ".strlen($str));
  20. echo $str;
  21. exit();
  22. }
  23. /**
  24. *
  25. * turn boolean to string
  26. */
  27. public static function boolToStr($bool){
  28. if(gettype($bool) == "string")
  29. return($bool);
  30. if($bool == true)
  31. return("true");
  32. else
  33. return("false");
  34. }
  35. /**
  36. *
  37. * convert string to boolean
  38. */
  39. public static function strToBool($str){
  40. if(is_bool($str))
  41. return($str);
  42. if(empty($str))
  43. return(false);
  44. if(is_numeric($str))
  45. return($str != 0);
  46. $str = strtolower($str);
  47. if($str == "true")
  48. return(true);
  49. return(false);
  50. }
  51. //------------------------------------------------------------
  52. // get black value from rgb value
  53. public static function yiq($r,$g,$b){
  54. return (($r*0.299)+($g*0.587)+($b*0.114));
  55. }
  56. /**
  57. *
  58. * convert colors to rgb
  59. */
  60. public static function html2rgb($color){
  61. if(empty($color))
  62. $color = "#000000";
  63. if ($color[0] == '#')
  64. $color = substr($color, 1);
  65. if (strlen($color) == 6)
  66. list($r, $g, $b) = array($color[0].$color[1],
  67. $color[2].$color[3],
  68. $color[4].$color[5]);
  69. elseif (strlen($color) == 3)
  70. list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
  71. else
  72. return false;
  73. $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
  74. return array($r, $g, $b);
  75. }
  76. //---------------------------------------------------------------------------------------------------
  77. // convert timestamp to time string
  78. public static function timestamp2Time($stamp){
  79. $strTime = date("H:i",$stamp);
  80. return($strTime);
  81. }
  82. //---------------------------------------------------------------------------------------------------
  83. // convert timestamp to date and time string
  84. public static function timestamp2DateTime($stamp){
  85. $strDateTime = date("d M Y, H:i",$stamp);
  86. return($strDateTime);
  87. }
  88. //---------------------------------------------------------------------------------------------------
  89. // convert timestamp to date string
  90. public static function timestamp2Date($stamp){
  91. $strDate = date("d M Y",$stamp); //27 Jun 2009
  92. return($strDate);
  93. }
  94. /**
  95. * get value from array. if not - return alternative
  96. */
  97. public static function getVal($arr,$key,$altVal=""){
  98. if(isset($arr[$key])) return($arr[$key]);
  99. return($altVal);
  100. }
  101. /**
  102. *
  103. * convert object to string.
  104. */
  105. public static function toString($obj){
  106. return(trim((string)$obj));
  107. }
  108. /**
  109. * remove utf8 bom sign
  110. */
  111. public static function remove_utf8_bom($content){
  112. $content = str_replace(chr(239),"",$content);
  113. $content = str_replace(chr(187),"",$content);
  114. $content = str_replace(chr(191),"",$content);
  115. $content = trim($content);
  116. return($content);
  117. }
  118. //------------------------------------------------------------
  119. // get variable from post or from get. get wins.
  120. public static function getPostGetVariable($name,$initVar = ""){
  121. $var = $initVar;
  122. if(isset($_POST[$name])) $var = $_POST[$name];
  123. else if(isset($_GET[$name])) $var = $_GET[$name];
  124. return($var);
  125. }
  126. //------------------------------------------------------------
  127. public static function getPostVariable($name,$initVar = ""){
  128. $var = $initVar;
  129. if(isset($_POST[$name])) $var = $_POST[$name];
  130. return($var);
  131. }
  132. //------------------------------------------------------------
  133. public static function getGetVar($name,$initVar = ""){
  134. $var = $initVar;
  135. if(isset($_GET[$name])) $var = $_GET[$name];
  136. return($var);
  137. }
  138. /**
  139. *
  140. * validate that some file exists, if not - throw error
  141. */
  142. public static function validateFilepath($filepath,$errorPrefix=null){
  143. if(file_exists($filepath) == true)
  144. return(false);
  145. if($errorPrefix == null)
  146. $errorPrefix = "File";
  147. $message = $errorPrefix." $filepath not exists!";
  148. self::throwError($message);
  149. }
  150. /**
  151. *
  152. * validate that some value is numeric
  153. */
  154. public static function validateNumeric($val,$fieldName=""){
  155. self::validateNotEmpty($val,$fieldName);
  156. if(empty($fieldName))
  157. $fieldName = "Field";
  158. if(!is_numeric($val))
  159. self::throwError("$fieldName should be numeric ");
  160. }
  161. /**
  162. *
  163. * validate that some variable not empty
  164. */
  165. public static function validateNotEmpty($val,$fieldName=""){
  166. if(empty($fieldName))
  167. $fieldName = "Field";
  168. if(empty($val) && is_numeric($val) == false)
  169. self::throwError("Field <b>$fieldName</b> should not be empty");
  170. }
  171. /**
  172. *
  173. * if directory not exists - create it
  174. * @param $dir
  175. */
  176. public static function checkCreateDir($dir){
  177. if(!is_dir($dir))
  178. mkdir($dir);
  179. if(!is_dir($dir))
  180. self::throwError("Could not create directory: $dir");
  181. }
  182. /**
  183. *
  184. * delete file, validate if deleted
  185. */
  186. public static function checkDeleteFile($filepath){
  187. if(file_exists($filepath) == false)
  188. return(false);
  189. $success = @unlink($filepath);
  190. if($success == false)
  191. self::throwError("Failed to delete the file: $filepath");
  192. }
  193. //------------------------------------------------------------
  194. //filter array, leaving only needed fields - also array
  195. public static function filterArrFields($arr,$fields){
  196. $arrNew = array();
  197. foreach($fields as $field){
  198. if(isset($arr[$field]))
  199. $arrNew[$field] = $arr[$field];
  200. }
  201. return($arrNew);
  202. }
  203. //------------------------------------------------------------
  204. //get path info of certain path with all needed fields
  205. public static function getPathInfo($filepath){
  206. $info = pathinfo($filepath);
  207. //fix the filename problem
  208. if(!isset($info["filename"])){
  209. $filename = $info["basename"];
  210. if(isset($info["extension"]))
  211. $filename = substr($info["basename"],0,(-strlen($info["extension"])-1));
  212. $info["filename"] = $filename;
  213. }
  214. return($info);
  215. }
  216. /**
  217. * Convert std class to array, with all sons
  218. * @param unknown_type $arr
  219. */
  220. public static function convertStdClassToArray($arr){
  221. $arr = (array)$arr;
  222. $arrNew = array();
  223. foreach($arr as $key=>$item){
  224. $item = (array)$item;
  225. $arrNew[$key] = $item;
  226. }
  227. return($arrNew);
  228. }
  229. //------------------------------------------------------------
  230. //save some file to the filesystem with some text
  231. public static function writeFile($str,$filepath){
  232. $fp = fopen($filepath,"w+");
  233. fwrite($fp,$str);
  234. fclose($fp);
  235. }
  236. //------------------------------------------------------------
  237. //save some file to the filesystem with some text
  238. public static function writeDebug($str,$filepath="debug.txt",$showInputs = true){
  239. $post = print_r($_POST,true);
  240. $server = print_r($_SERVER,true);
  241. if(getType($str) == "array")
  242. $str = print_r($str,true);
  243. if($showInputs == true){
  244. $output = "--------------------"."\n";
  245. $output .= $str."\n";
  246. $output .= "Post: ".$post."\n";
  247. }else{
  248. $output = "---"."\n";
  249. $output .= $str . "\n";
  250. }
  251. if(!empty($_GET)){
  252. $get = print_r($_GET,true);
  253. $output .= "Get: ".$get."\n";
  254. }
  255. //$output .= "Server: ".$server."\n";
  256. $fp = fopen($filepath,"a+");
  257. fwrite($fp,$output);
  258. fclose($fp);
  259. }
  260. /**
  261. *
  262. * clear debug file
  263. */
  264. public static function clearDebug($filepath = "debug.txt"){
  265. if(file_exists($filepath))
  266. unlink($filepath);
  267. }
  268. /**
  269. *
  270. * save to filesystem the error
  271. */
  272. public static function writeDebugError(Exception $e,$filepath = "debug.txt"){
  273. $message = $e->getMessage();
  274. $trace = $e->getTraceAsString();
  275. $output = $message."\n";
  276. $output .= $trace."\n";
  277. $fp = fopen($filepath,"a+");
  278. fwrite($fp,$output);
  279. fclose($fp);
  280. }
  281. //------------------------------------------------------------
  282. //save some file to the filesystem with some text
  283. public static function addToFile($str,$filepath){
  284. $fp = fopen($filepath,"a+");
  285. fwrite($fp,"---------------------\n");
  286. fwrite($fp,$str."\n");
  287. fclose($fp);
  288. }
  289. //--------------------------------------------------------------
  290. //check the php version. throw exception if the version beneath 5
  291. private static function checkPHPVersion(){
  292. $strVersion = phpversion();
  293. $version = (float)$strVersion;
  294. if($version < 5) throw new Exception("You must have php5 and higher in order to run the application. Your php version is: $version");
  295. }
  296. //--------------------------------------------------------------
  297. // valiadte if gd exists. if not - throw exception
  298. private static function validateGD(){
  299. if(function_exists('gd_info') == false)
  300. throw new Exception("You need GD library to be available in order to run this application. Please turn it on in php.ini");
  301. }
  302. //--------------------------------------------------------------
  303. //return if the json library is activated
  304. public static function isJsonActivated(){
  305. return(function_exists('json_encode'));
  306. }
  307. /**
  308. *
  309. * encode array into json for client side
  310. */
  311. public static function jsonEncodeForClientSide($arr){
  312. $json = "";
  313. if(!empty($arr)){
  314. $json = json_encode($arr);
  315. $json = addslashes($json);
  316. }
  317. $json = "'".$json."'";
  318. return($json);
  319. }
  320. /**
  321. *
  322. * decode json from the client side
  323. */
  324. public static function jsonDecodeFromClientSide($data){
  325. $data = stripslashes($data);
  326. $data = str_replace('&#092;"','\"',$data);
  327. $data = json_decode($data);
  328. $data = (array)$data;
  329. return($data);
  330. }
  331. //--------------------------------------------------------------
  332. //validate if some directory is writable, if not - throw a exception
  333. private static function validateWritable($name,$path,$strList,$validateExists = true){
  334. if($validateExists == true){
  335. //if the file/directory doesn't exists - throw an error.
  336. if(file_exists($path) == false)
  337. throw new Exception("$name doesn't exists");
  338. }
  339. else{
  340. //if the file not exists - don't check. it will be created.
  341. if(file_exists($path) == false) return(false);
  342. }
  343. if(is_writable($path) == false){
  344. chmod($path,0755); //try to change the permissions
  345. if(is_writable($path) == false){
  346. $strType = "Folder";
  347. if(is_file($path)) $strType = "File";
  348. $message = "$strType $name is doesn't have a write permissions. Those folders/files must have a write permissions in order that this application will work properly: $strList";
  349. throw new Exception($message);
  350. }
  351. }
  352. }
  353. //--------------------------------------------------------------
  354. //validate presets for identical keys
  355. public static function validatePresets(){
  356. global $g_presets;
  357. if(empty($g_presets)) return(false);
  358. //check for duplicates
  359. $assoc = array();
  360. foreach($g_presets as $preset){
  361. $id = $preset["id"];
  362. if(isset($assoc[$id]))
  363. throw new Exception("Double preset ID detected: $id");
  364. $assoc[$id] = true;
  365. }
  366. }
  367. //--------------------------------------------------------------
  368. //Get url of image for output
  369. public static function getImageOutputUrl($filename,$width=0,$height=0,$exact=false){
  370. //exact validation:
  371. if($exact == "true" && (empty($width) || empty($height) ))
  372. self::throwError("Exact must have both - width and height");
  373. $url = CMGlobals::$URL_GALLERY."?img=".$filename;
  374. if(!empty($width))
  375. $url .= "&w=".$width;
  376. if(!empty($height))
  377. $url .= "&h=".$height;
  378. if($exact == true)
  379. $url .= "&t=exact";
  380. return($url);
  381. }
  382. /**
  383. *
  384. * get list of all files in the directory
  385. * ext - filter by his extension only
  386. */
  387. public static function getFileList($path,$ext=""){
  388. $dir = scandir($path);
  389. $arrFiles = array();
  390. foreach($dir as $file){
  391. if($file == "." || $file == "..") continue;
  392. if(!empty($ext)){
  393. $info = pathinfo($file);
  394. $extension = UniteFunctionsRev::getVal($info, "extension");
  395. if($ext != strtolower($extension))
  396. continue;
  397. }
  398. $filepath = $path . "/" . $file;
  399. if(is_file($filepath)) $arrFiles[] = $file;
  400. }
  401. return($arrFiles);
  402. }
  403. /**
  404. *
  405. * get list of all files in the directory
  406. */
  407. public static function getFoldersList($path){
  408. $dir = scandir($path);
  409. $arrFiles = array();
  410. foreach($dir as $file){
  411. if($file == "." || $file == "..") continue;
  412. $filepath = $path . "/" . $file;
  413. if(is_dir($filepath)) $arrFiles[] = $file;
  414. }
  415. return($arrFiles);
  416. }
  417. /**
  418. *
  419. * do "trim" operation on all array items.
  420. */
  421. public static function trimArrayItems($arr){
  422. if(gettype($arr) != "array")
  423. UniteFunctionsRev::throwError("trimArrayItems error: The type must be array");
  424. foreach ($arr as $key=>$item)
  425. $arr[$key] = trim($item);
  426. return($arr);
  427. }
  428. /**
  429. *
  430. * get url contents
  431. */
  432. public static function getUrlContents($url,$arrPost=array(),$method = "post",$debug=false){
  433. $ch = curl_init();
  434. $timeout = 0;
  435. $strPost = '';
  436. foreach($arrPost as $key=>$value){
  437. if(!empty($strPost))
  438. $strPost .= "&";
  439. $value = urlencode($value);
  440. $strPost .= "$key=$value";
  441. }
  442. //set curl options
  443. if(strtolower($method) == "post"){
  444. curl_setopt($ch, CURLOPT_POST, 1);
  445. curl_setopt($ch, CURLOPT_POSTFIELDS,$strPost);
  446. }
  447. else //get
  448. $url .= "?".$strPost;
  449. //remove me
  450. //Functions::addToLogFile(SERVICE_LOG_SERVICE, "url", $url);
  451. curl_setopt($ch, CURLOPT_URL, $url);
  452. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  453. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  454. $headers = array();
  455. $headers[] = "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
  456. $headers[] = "Accept-Charset:utf-8;q=0.7,*;q=0.7";
  457. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  458. $response = curl_exec($ch);
  459. if($debug == true){
  460. dmp($url);
  461. dmp($response);
  462. exit();
  463. }
  464. if($response == false)
  465. throw new Exception("getUrlContents Request failed");
  466. curl_close($ch);
  467. return($response);
  468. }
  469. /**
  470. *
  471. * get link html
  472. */
  473. public static function getHtmlLink($link,$text,$id="",$class=""){
  474. if(!empty($class))
  475. $class = " class='$class'";
  476. if(!empty($id))
  477. $id = " id='$id'";
  478. $html = "<a href=\"$link\"".$id.$class.">$text</a>";
  479. return($html);
  480. }
  481. /**
  482. *
  483. * get select from array
  484. */
  485. public static function getHTMLSelect($arr,$default="",$htmlParams="",$assoc = false){
  486. $html = "<select $htmlParams>";
  487. foreach($arr as $key=>$item){
  488. $selected = "";
  489. if($assoc == false){
  490. if($item == $default) $selected = " selected ";
  491. }
  492. else{
  493. if(trim($key) == trim($default))
  494. $selected = " selected ";
  495. }
  496. if($assoc == true)
  497. $html .= "<option $selected value='$key'>$item</option>";
  498. else
  499. $html .= "<option $selected value='$item'>$item</option>";
  500. }
  501. $html.= "</select>";
  502. return($html);
  503. }
  504. /**
  505. *
  506. * Convert array to assoc array by some field
  507. */
  508. public static function arrayToAssoc($arr,$field=null){
  509. $arrAssoc = array();
  510. foreach($arr as $item){
  511. if(empty($field))
  512. $arrAssoc[$item] = $item;
  513. else
  514. $arrAssoc[$item[$field]] = $item;
  515. }
  516. return($arrAssoc);
  517. }
  518. /**
  519. *
  520. * convert assoc array to array
  521. */
  522. public static function assocToArray($assoc){
  523. $arr = array();
  524. foreach($assoc as $item)
  525. $arr[] = $item;
  526. return($arr);
  527. }
  528. /**
  529. *
  530. * strip slashes from textarea content after ajax request to server
  531. */
  532. public static function normalizeTextareaContent($content){
  533. if(empty($content))
  534. return($content);
  535. $content = stripslashes($content);
  536. $content = trim($content);
  537. return($content);
  538. }
  539. /**
  540. *
  541. * get random array item
  542. */
  543. public static function getRandomArrayItem($arr){
  544. $numItems = count($arr);
  545. $rand = rand(0, $numItems-1);
  546. $item = $arr[$rand];
  547. return($item);
  548. }
  549. /**
  550. *
  551. * recursive delete directory or file
  552. */
  553. public static function deleteDir($path,$deleteOriginal = true, $arrNotDeleted = array(),$originalPath = ""){
  554. if(empty($originalPath))
  555. $originalPath = $path;
  556. //in case of paths array
  557. if(getType($path) == "array"){
  558. $arrPaths = $path;
  559. foreach($path as $singlePath)
  560. $arrNotDeleted = self::deleteDir($singlePath,$deleteOriginal,$arrNotDeleted,$originalPath);
  561. return($arrNotDeleted);
  562. }
  563. if(!file_exists($path))
  564. return($arrNotDeleted);
  565. if(is_file($path)){ // delete file
  566. $deleted = unlink($path);
  567. if(!$deleted)
  568. $arrNotDeleted[] = $path;
  569. }
  570. else{ //delete directory
  571. $arrPaths = scandir($path);
  572. foreach($arrPaths as $file){
  573. if($file == "." || $file == "..")
  574. continue;
  575. $filepath = realpath($path."/".$file);
  576. $arrNotDeleted = self::deleteDir($filepath,$deleteOriginal,$arrNotDeleted,$originalPath);
  577. }
  578. if($deleteOriginal == true || $originalPath != $path){
  579. $deleted = @rmdir($path);
  580. if(!$deleted)
  581. $arrNotDeleted[] = $path;
  582. }
  583. }
  584. return($arrNotDeleted);
  585. }
  586. /**
  587. * copy folder to another location.
  588. *
  589. */
  590. public static function copyDir($source,$dest,$rel_path = "",$blackList = null){
  591. $full_source = $source;
  592. if(!empty($rel_path))
  593. $full_source = $source."/".$rel_path;
  594. $full_dest = $dest;
  595. if(!empty($full_dest))
  596. $full_dest = $dest."/".$rel_path;
  597. if(!is_dir($full_source))
  598. self::throwError("The source directroy: '$full_source' not exists.");
  599. if(!is_dir($full_dest))
  600. mkdir($full_dest);
  601. $files = scandir($full_source);
  602. foreach($files as $file){
  603. if($file == "." || $file == "..")
  604. continue;
  605. $path_source = $full_source."/".$file;
  606. $path_dest = $full_dest."/".$file;
  607. //validate black list
  608. $rel_path_file = $file;
  609. if(!empty($rel_path))
  610. $rel_path_file = $rel_path."/".$file;
  611. //if the file or folder is in black list - pass it
  612. if(array_search($rel_path_file, $blackList) !== false)
  613. continue;
  614. //if file - copy file
  615. if(is_file($path_source)){
  616. copy($path_source,$path_dest);
  617. }
  618. else{ //if directory - recursive copy directory
  619. if(empty($rel_path))
  620. $rel_path_new = $file;
  621. else
  622. $rel_path_new = $rel_path."/".$file;
  623. self::copyDir($source,$dest,$rel_path_new,$blackList);
  624. }
  625. }
  626. }
  627. }
  628. ?>