source: pro-violet-viettel/sourcecode/api.violet.vn/www/lib/common/myUtility.class.php @ 289

Last change on this file since 289 was 289, checked in by dungnv, 11 years ago
File size: 19.6 KB
Line 
1<?php
2  class myUtility {
3    static $log_dir = null;
4
5    /**
6     * Return extension of a file name
7     *
8     */
9    public static function getFileExt($fileName) {
10      $names = explode('.', $fileName);
11      $i = count($names);
12      if ($i>0) return  strtolower($names[$i-1]); else return '';
13    }
14
15    /**
16     * return file name (no extension)
17     *
18     *
19     * @param String $fileName
20     */
21    public static function getFileName($fileName) {
22      $names = explode('.', $fileName);
23      $i = count($names);
24      if (count($names)>0) array_pop($names);
25      return join('.', $names);
26    }
27
28    /**
29     * return safe file name (lower byte character)
30     *
31     * @param unknown_type $fileName
32     */
33    public static function getSafeFileName($fileName) {
34      $names = explode('.', $fileName);
35      $ext = array_pop($names);
36      $safe = preg_replace('@[^A-Za-z0-9_]+@', '', join($names));
37      if ($safe=='') $safe = '0';
38      return $safe.'.'.$ext;
39    }
40
41    /**
42     * Convert from UTF-8 to non mark Vietnamese text
43     *
44     * @param String $value: input text
45     * @return Non marke Vietnamese text
46     */
47    public static function vietDecode($value)
48    {
49      $vietChar         = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|Ú|ẻ|ẜ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|Æ¡|ớ|ờ|ở|ỡ|ợ|ÃŽ|ố|ồ|ổ|ỗ|ộ|ú|ù|á»§|Å©|ụ|ư|ứ|ừ|á»­|ữ|á»±|í|ì|ỉ|Ä©|ị|Ü|ỳ|á»·|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẏ|Ặ|Â|Ẁ|Ẋ|ẚ|Ẫ|Ậ|É|È|Ẻ|Ẍ|ẞ|Ê|ẟ|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Æ |Ớ|Ờ|Ở|á» |Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ị|Åš|Ề|Ư|Ớ|Ừ|Ử|á»®|á»°|Í|Ì|Ỉ|Äš|Ị|Ý|Ỳ|á»¶|Ở|Ỏ|Đ';
50                        $engChar        = 'a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|e|e|e|e|e|e|e|e|e|e|e|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|u|u|u|u|u|u|u|u|u|u|u|i|i|i|i|i|y|y|y|y|y|d|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|E|E|E|E|E|E|E|E|E|E|E|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|U|U|U|U|U|U|U|U|U|U|U|I|I|I|I|I|Y|Y|Y|Y|Y|D';
51                        $arrVietChar    = explode('|', $vietChar);
52                        $arrEngChar             = explode('|', $engChar);
53                        return str_replace($arrVietChar, $arrEngChar, $value);
54    }
55
56    public static function getUrlName($name) {
57      $name = strtolower(myUtility::vietDecode($name));
58      $name = preg_replace('@[^\w\d_]+@', '', $name);
59      return $name;
60    }
61
62    /**
63     * Check hard disk for not exist fileName, if file exists, change it name
64     *
65     * @param unknown_type $pathName
66     * @param unknown_type $fileName
67     * @param unknown_type $extName
68     */
69    public static function GetNoDuplicateFileName($pathName, &$fileName, $extName) {
70      $i = 0;
71      $newFileName = $fileName;
72      while (file_exists("$pathName/$newFileName.$extName")) {
73        $newFileName = $fileName . (++$i);
74      }
75      $fileName = $newFileName;
76    }
77
78    public static function moveDirectory($src, $dst) {
79      if (!is_dir($dst)) {umask(0); mkdir($dst, 0777, true);}
80      foreach (scandir($src) as $file) {
81        if ($file=='.' || $file=='..') continue;
82        $srcm = $src.'/'.$file;
83        $dstm = $dst.'/'.$file;
84        if (is_dir($srcm)) myUtility::moveDirectory($srcm, $dstm);
85        else {
86          rename($srcm, $dstm);
87          chmod($dstm, 0777);
88        }
89      }
90      rmdir($src);
91    }
92
93    public static function cleanDirectory($path) {
94      foreach (scandir($path) as $dir) {
95        if ($dir=='.' || $dir=='..') continue;
96        $dname = $path.'/'.$dir;
97        if (is_dir($dname)) self::cleanDirectory($dname);
98        else if (is_file($dname)) unlink($dname);
99      }
100      rmdir($path);
101    }
102
103    public static function ScaleAspect(&$width, &$height, $maxWidth, $maxHeight) {
104      $sx = $maxWidth / $width;
105      $sy = $maxHeight / $height;
106      if ($sx>$sy) $sx = $sy;
107      $width = round($width * $sx / 2) * 2;
108      $height = round($height * $sx / 2) * 2;
109    }
110
111    /**
112     * Enter description here...
113     *
114     * @param unknown_type $fileName
115     * @param unknown_type $fileThumb
116     * @param unknown_type $time
117     * @param unknown_type $info
118     * @return unknown
119     */
120    public static function FlvToThumbnail($fileName, $fileThumb, $time = null, $info = null) {
121      try {
122        if ($info==null) $info = self::GetVideoInfo($fileName);
123
124        if (!isset($info['ID_VIDEO_FORMAT'])) return false;
125        if (!isset($info['ID_LENGTH'])) return false;
126        $width = doubleval($info['ID_VIDEO_WIDTH']);
127        $height = doubleval($info['ID_VIDEO_HEIGHT']);
128
129        self::ScaleAspect($width, $height, 150, 100);
130
131        if ($time===null) $time = doubleval($info['ID_LENGTH']) / 2;
132
133        $logFileName = 'convert_flv_thumb.log';
134
135        // no .THM file so need to use ffmpeg to get tumbnail image
136                //ffmpeg -y -i MVI_6640.AVI -s qcif -f mjpeg -t 0.001 movie.jpg
137                $ffmpeg_cmd = sfConfig::get('app_ffmpeg_exe');
138                $command = "$ffmpeg_cmd -y -v 0 -itsoffset -$time -i ". escapeshellarg($fileName) ." -s {$width}x{$height} -f mjpeg -vframes 1 ". escapeshellarg($fileThumb);
139                //myUtility::log("\n\n\n********".$command, $logFileName);
140
141                $descriptorspec = array(
142           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
143           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
144           2 => array("pipe", "w"),  // stdout is a pipe that the child will write to
145        );
146        $process = proc_open($command, $descriptorspec, $pipes);
147        if (is_resource($process)) {
148          $ret = true;
149          while (!feof($pipes[2])) {
150            $line = fgets($pipes[2],1024);
151            //myUtility::log($line, $logFileName);
152            if (preg_match('@: no such file or directory@', $line)) $ret = false;
153            if (preg_match('@^Error while opening codec for output stream@', $line)) $ret = false;
154            if (preg_match('@Unknown format@', $line)) $ret = false;
155          }
156          fclose($pipes[2]);
157          proc_close($process);
158          return $ret;
159        } else return false;
160      } catch (Exception $e) {
161        myUtility::log($e->getMessage(), $logFileName);
162        return false;
163      }
164    }
165
166    public static function ImageToJpg($imageName, $jpgName) {
167      $convert_cmd = sfConfig::get('app_convert_exe');
168      $command = "$convert_cmd ". escapeshellarg($imageName) ." ". escapeshellarg($jpgName);
169      $descriptorspec = array(
170         0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
171         1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
172      );
173      $process = proc_open($command, $descriptorspec, $pipes);
174      if (is_resource($process)) {
175        while (!feof($pipes[1])) {
176          $line = fgets($pipes[1], 1024);
177        }
178        fclose($pipes[1]);
179        proc_close($process);
180      }
181    }
182
183    public static function MovieToFlv($movieName, $flvName) {
184      try {
185        $logFileName = 'convert_flv.log';
186        $ffmpeg_cmd = sfConfig::get('app_ffmpeg_exe');
187
188                // generate the Flash FLV version of the file
189        // cif = 352x288
190        $command = "$ffmpeg_cmd -y -v 0 -i ". escapeshellarg($movieName) ." -s cif -ar 44100 -r 15 ". escapeshellarg($flvName);
191        //myUtility::log("\n\n\n********".$command, $logFileName);
192
193        $descriptorspec = array(
194           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
195           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
196           2 => array("pipe", "w"),  // stdout is a pipe that the child will write to
197        );
198        $process = proc_open($command, $descriptorspec, $pipes);
199        if (is_resource($process)) {
200          $ret = true;
201          while (!feof($pipes[2])) {
202            $line = fgets($pipes[2],1024);
203            //myUtility::log($line, $logFileName);
204            if (preg_match('@: no such file or directory@', $line)) $ret = false;
205            if (preg_match('@^Error while opening codec for output stream@', $line)) $ret = false;
206            if (preg_match('@Unknown format@', $line)) $ret = false;
207          }
208          fclose($pipes[2]);
209          proc_close($process);
210          return $ret;
211        } else return false;
212      } catch (Exception $e) {
213        myUtility::log($e->getMessage(), $logFileName);
214        return false;
215      }
216    }
217
218    /**
219     * Get Video info
220     *
221     * @param unknown_type $movieName
222     * @return array of info
223     *   'ID_VIDEO_WIDTH' => width of video
224     *   'ID_VIDEO_HEIGHT' => height of video
225     *   'ID_LENGTH' => lengh of video (in second)
226     *   'ID_VIDEO_FORMAT' => video codec
227     *   'ID_AUDIO_FORMAT' => audio codec
228     */
229    public static function GetVideoInfo($movieName) {
230      try {
231        $logFileName = 'video_info.log';
232        $mplayer_cmd = sfConfig::get('app_mplayer_exe');
233
234                // generate the Flash FLV version of the file
235        // cif = 352x288
236        $command = "$mplayer_cmd -identify " . escapeshellarg($movieName) ." -ao null -vo null -frames 0";
237        //myUtility::log("\n\n\n********".$command, $logFileName);
238
239        $descriptorspec = array(
240           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
241           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
242           2 => array("pipe", "w"),  // stdout is a pipe that the child will write to
243        );
244        $process = proc_open($command, $descriptorspec, $pipes);
245        if (is_resource($process)) {
246          $ret = array();
247          while (!feof($pipes[1])) {
248            $line = fgets($pipes[1],1024);
249            //myUtility::log($line, $logFileName);
250            if (preg_match('@ID_VIDEO_FORMAT|ID_VIDEO_WIDTH|ID_VIDEO_HEIGHT|ID_AUDIO_FORMAT|ID_LENGTH@', $line)) {
251              $col = explode('=', trim($line));
252              $ret[$col[0]] = $col[1];
253            }
254          }
255          fclose($pipes[1]);
256          proc_close($process);
257          return $ret;
258        } else return false;
259      } catch (Exception $e) {
260        myUtility::log($e->getMessage(), $logFileName);
261        return array();
262      }
263    }
264
265    public static function SizeImage($maxWidth, $maxHW, $fileName, $thumbFileName, $allowBigger=true, $externalFileName=false) {
266      try {
267        $logFileName = 'convert_img.log';
268
269        $width = intval($maxWidth); $height = intval($maxHW);
270        if ($width==null || $height==null) return false;
271        if (false==$allowBigger) {
272          list($mwidth, $mheight) = myUtility::getImageSize($fileName, $externalFileName);
273          if ($mwidth==0 || $mheight==0) return  false;
274          $mwidth = intval($mwidth); $mheight = intval($mheight);
275          if ($mwidth<=$width && $mheight<=$height) {
276            $width = $mwidth;
277            $height = $mheight;
278          }
279        }
280
281        $img_cmd = sfConfig::get('app_convert_exe');
282        if ($externalFileName)
283          $fileName = '"'.$fileName.'"';
284        else
285          $fileName = escapeshellarg($fileName);
286        $command = "$img_cmd -resize {$width}x{$height} -flatten -background white -verbose " . $fileName . ' ' . escapeshellarg($thumbFileName);
287        //myUtility::log("Execute ".$command, $logFileName, "\n");
288
289        $descriptorspec = array(
290           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
291           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
292        );
293        $process = proc_open($command, $descriptorspec, $pipes);
294
295        if (is_resource($process)) {
296          $ret = true;
297          while (!feof($pipes[1])) {
298            $line = fgets($pipes[1],1024);
299            //if ($line != '') myUtility::log($line, $logFileName);
300            if (preg_match('@missing an image filename@', $line)) $ret = false;
301          }
302          fclose($pipes[1]);
303          proc_close($process);
304          return $ret;
305        }
306        return false;
307      } catch (Exception $e) {
308        myUtility::log($e->getMessage(), $logFileName);
309        return false;
310      }
311    }
312
313    public static function FlvAddMeta($fileName) {
314      try {
315        $logFileName = 'meta_flv.log';
316        $img_cmd = sfConfig::get('app_flvtool2_exe');
317
318        $command = "$img_cmd -U " . escapeshellarg($fileName);
319        $descriptorspec = array(
320           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
321           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
322        );
323        //myUtility::log($command, $logFileName);
324        $process = proc_open($command, $descriptorspec, $pipes);
325
326        if (is_resource($process)) {
327          $ret = true;
328          while (!feof($pipes[1])) {
329            //myUtility::log($line, $logFileName);
330            $line = fgets($pipes[1],1024);
331          }
332          fclose($pipes[1]);
333          proc_close($process);
334          return $ret;
335        } else return false;
336      } catch (Exception $e) {
337        myUtility::log($e->getMessage(), $logFileName);
338        return false;
339      }
340    }
341
342    public static function getSWFImageSize($fileName) {
343      try {
344        $width = 640;
345        $height = 480;
346
347        $img_cmd =sfConfig::get('app_swfdump_exe');
348        $command = "$img_cmd -X -Y " . escapeshellarg($fileName);
349        $descriptorspec = array(
350           0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
351           1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
352        );
353        $process = proc_open($command, $descriptorspec, $pipes);
354
355        if (is_resource($process)) {
356          while (!feof($pipes[1])) {
357            $line = fgets($pipes[1],1024);
358            if (preg_match('@-X ([0-9]+) -Y ([0-9]+)@', $line, $size)) {
359              $width = intval($size[1]);
360              $height = intval($size[2]);
361            }
362          }
363          fclose($pipes[1]);
364          proc_close($process);
365        }
366        return array($width, $height);
367      } catch (Exception $e) {
368        return array($width, $height);
369      }
370    }
371
372    public static function getImageSize($fileName, $externalFile=false) {
373
374      $length = strlen($fileName);
375      $ext = $length>3?substr($fileName, $length-3, 3):'';
376      $ext = strtolower($ext);
377      if ($ext=='swf') return self::getSWFImageSize($fileName);
378      $width = 0;
379      $height = 0;
380
381      if ($externalFile)
382        $fileName = '"'.$fileName.'"';
383      else
384        $fileName = escapeshellarg($fileName);
385
386      $img_cmd = sfConfig::get('app_identify_exe');
387      $command = "$img_cmd -format %wx%h\\n " . $fileName;
388      $descriptorspec = array(
389         0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
390         1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
391      );
392      $process = proc_open($command, $descriptorspec, $pipes);
393
394      if (is_resource($process)) {
395        $ret = true;
396        while (!feof($pipes[1])) {
397          $line = trim(fgets($pipes[1],1024));
398          if (preg_match('@Improper image header@', $line)) $ret = false;
399          if (preg_match('@Not a JPEG file@', $line)) $ret = false;
400          if (preg_match('@no decode delegate for this image format@', $line)) $ret = false;
401          if ($line!=null) {
402            if ($width == null && preg_match('@([0-9]+)x([0-9]+)@', $line, $size)) {
403              $width = intval($size[1]);
404              $height = intval($size[2]);
405            }
406          }
407        }
408        fclose($pipes[1]);
409        proc_close($process);
410      } else $ret = false;
411      return array($width, $height);
412    }
413
414    public static function global_image_tag($fileName, $width, $height, $vars = null) {
415      $ext = myUtility::getFileExt($fileName);
416      switch ($ext) {
417        case 'swf':
418          return flash_tag($fileName, $width, $height, $vars, true);
419        default:
420          return image_tag($fileName, array('width'=>$width, 'height'=>$height));
421      }
422    }
423
424    public static function redirectWithCustomReferer($host, $retHost='', $param = null) {
425      echo "
426            <head>
427              <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
428            </head>
429            <form method='post' action='$host'>
430              <input type='hidden' id='ret' name='ret' value='$retHost'/>
431            </form>
432            Xin quÜ vị đợi giây lát... Nếu trang web khÃŽng tá»± động chuyển, hãy <a href='#' onclick='submitform()'>Click vào đây</a>
433            <script>
434              function submitform() {
435                document.forms[0].submit();
436              }
437              window.setTimeout('submitform()',50);
438            </script>
439           ";
440      exit();
441    }
442
443    /**
444     * execute native sql
445     *
446     * @param unknown_type $sql
447     * @return array of rows, each row is an array of fields (no key)
448     */
449    public static function execSql($sql, $noResult = false) {
450      $criteria = new Criteria();
451      $dbMap = Propel::getDatabaseMap($criteria->getDbName());
452      $db = Propel::getDB($criteria->getDbName());
453
454      $con = Propel::getConnection($criteria->getDbName(), Propel::CONNECTION_READ);
455
456      $stmt = $con->prepare($sql);
457      $stmt->execute();
458      if ($noResult==true) return;
459      $rows = array();
460      try {
461        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
462          $rows[] = $row;
463        }
464      } catch (Exception $e) {}
465      $stmt->closeCursor();
466      return $rows;
467    }
468
469    public static function log($message, $fileName = 'blog.log', $prefix = '') {
470      if (null == self::$log_dir) self::$log_dir = sfConfig::get('sf_log_dir');
471      error_log($prefix.date('Y-m-d H:i:s ').substr(session_id(), 0, 5).' '.$message."\n", 3, self::$log_dir.'/'.$fileName);
472    }
473
474    public static function track_upload($message, $logFile) {
475      error_log(date('H:i:s ').$message."\n", 3, sfConfig::get('sf_web_dir').'/uploads/previews/upinfo/'.$logFile.'_'.date('Ymd').'.log');
476    }
477
478    /**
479     * Truncates +text+ to the length of +length+ and replaces the last three characters with the +truncate_string+
480     * if the +text+ is longer than +length+.
481     */
482    public static function mb_truncate_text($text, $length = 33, $truncate_string = '...', $truncate_lastspace = false)
483    {
484      if ($text == '') {
485        return '';
486      }
487
488      if (mb_strlen($text, 'utf8') > $length) {
489        $truncate_text = mb_substr($text, 0, $length - strlen($truncate_string), 'utf8');
490        if ($truncate_lastspace) {
491          $truncate_text = preg_replace('/\s+?(\S+)?$/', '', $truncate_text);
492        }
493
494        return $truncate_text.$truncate_string;
495      }
496      else {
497        return $text;
498      }
499    }
500
501    public static function htmlToText($str) {
502      $text = new html2text($str);
503      return $text->get_text();
504    }
505
506    /**
507     * Return first day of week that include $date
508     *
509     * @param string $date (not include time)
510     * @return string first day of week
511     */
512    public static function dateToWeek($date) {
513      $time = strtotime($date);
514      $dayOfWeek = date('w', $time);
515      return date('Y-m-d', strtotime("$date -$dayOfWeek day"));
516    }
517
518    /**
519     * Create random password
520     *
521     * @param int $lenght: length of random password
522     * @return password
523     */
524    public function create_password($length = 6)
525    {
526      $chars = '0123456789';
527      srand(time());
528      $pass = '';
529      for ($i = 0; $i < $length; $i++) {
530        $num = rand(0, strlen($chars)-1);
531        $pass .= $chars[$num];
532      }
533      return $pass;
534    }
535
536    public function getRealIpAddr() {
537      if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
538        $ip = $_SERVER['HTTP_CLIENT_IP'];
539      } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  //to check ip is pass from proxy
540        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
541      } else {
542        $ip = $_SERVER['REMOTE_ADDR'];
543      }
544      return $ip;
545    }
546
547    public function validate($filterclass, &$data, &$error) {
548      $filter = new $filterclass();
549      $filter->initialize(null);
550      return $filter->execute($data, $error);
551    }
552  }
553?>
Note: See TracBrowser for help on using the repository browser.