Guest User

Untitled

a guest
Dec 16th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. <?php
  2. class PuploadBehavior extends ModelBehavior{
  3. var $Model = null;
  4. var $options = array(
  5. 'dir' => 'img'
  6. );
  7. var $empfields = array();
  8. var $allowExtension = array('txt','pdf','jpg','jpeg','png','flv','mp3');
  9. var $errors = array();
  10.  
  11.  
  12. function setup(&$model, $settings = array()){
  13. $this->Model = $model;
  14. $this->options['mname'] = $model->alias;
  15. if(!empty($settings['fields'])) $this->options['fields'] = $settings['fields'];
  16. }
  17.  
  18.  
  19. function beforeSave(){
  20. $this->doUpload();
  21. }
  22.  
  23. function doUpload(){
  24. $als = $this->options['mname'];
  25. foreach($this->options['fields'] as $field){
  26. if(empty($this->Model->data[$als][$field]['name'])){
  27. $this->empfields[] = $field;
  28. unset($this->Model->data[$als][$field]);
  29. }
  30. else {
  31. $filename = explode('.', $this->Model->data[$als][$field]['name']);
  32. $ext = end($filename);
  33. if($this->whiteList($ext)){
  34. $p = $this->makepath($field);
  35. if(!empty($p)){
  36. if(file_exists($p . '/' . implode('.', $filename))) $filename[0] = $filename[0] . '-' . time();
  37. if(move_uploaded_file($this->Model->data[$als][$field]['tmp_name'], $p . '/' . implode('.', $filename))){
  38. $this->Model->data[$als][$field] = implode('.', $filename);
  39. } else $this->errors[$field][] = 'upload field';
  40. }
  41. }
  42. }
  43. }
  44. }
  45.  
  46. function whiteList($ext = null){
  47. if(in_array($ext, $this->allowExtension)) return true;
  48. else return false;
  49. }
  50.  
  51. function makepath($field = null){
  52. $mpath = WWW_ROOT . $this->options['dir'] . '/' . $this->Model->alias . '/' . $field;
  53. $steps = explode('/', $mpath);
  54. unset($steps[0]);
  55. $dirs = null;
  56. foreach($steps as $dir){
  57. $dirs = $dirs . '/' . $dir;
  58. if(!is_dir($dirs)) mkdir($dirs, 0777);
  59. }
  60. if(!is_dir($mpath)){
  61. if(mkdir($mpath, 0775)) return $mpath;
  62. else {
  63. $this->errors[$field] [] = 'path not found';
  64. return false;
  65. }
  66. } else return $mpath;
  67.  
  68. }
  69. }
Add Comment
Please, Sign In to add comment