summaryrefslogtreecommitdiff
path: root/public/upload.php
blob: 1ed278db1b2cac7fdafb60c07b3637eec9f6288f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
// Upload image
// proccess is called via url:
// upload.php ? id = X [&sec = 1] [&del = Y]
// X : item ID
// Y : old image file
// &sec=1 : declares the image as "2nd" image of the item
// --- -- -- - - -
// Workline:
// 1. Validate input
// 2. Check common errors
// -- If everything is ok:
// 3. Upload image
// 4. Make a thumbnail of the image
// 5. Update database record
// ---
// last update: 2020-06-21
////////////////////////////////////////////////////////////////////////////////


include("config/parametres.php");

  // #1.  VALIDATE input and init paremetres of the script
  // --- -- -- - - -
  // valid record id exist
  // validate delete image (if exist)
  // calculate filenames, file-extensions, paths etc.
  //////////////////////////////////////////////////////////////////////////////

  // validate 'id'
  // ---------------------------------------------------------------------------
  if (isset($_GET['id']) && is_numeric($_GET['id']) && (($_GET['id'] != '0'))) {
      $id  = $_GET['id'];                 // id of photo to upload
      $sub_dir = intdiv($id, FOLDER_CPC) .'/';    // subdirectory to put the image
          // each subdir hosts up to 256 items and 1024 images
          // 256 items x (2 imgs + 2 thumbs) = 1024
  }
  else {
      echo '{"success": false, "err" : "ID ERROR"}'; die();
  }

  // validate 'sec' parameter (if this is the SECOND image of the item)
  // ---------------------------------------------------------------------------
  if (isset($_GET['sec']) && is_numeric($_GET['sec']) && (($_GET['sec'] == '1'))) {
      define("IS_2ND_IMG", true);  // is second image of item
  }
  else {
      define("IS_2ND_IMG", false);
  }

  // validate 'del' imagefile
  // ---------------------------------------------------------------------------
  if ( isset($_GET['del'])
      && ( preg_match('/^(\d+)_([A-Fa-f0-9]{5})\.jpg/',$_GET['del']) )   // match filename format: ID_HEX{5}.jpg
      && ( explode( "_", $_GET['del'] )[0] == $id )                // ID part of file is same as $id
      && file_exists( UPLOAD_DIR. $sub_dir . $_GET['del'] ) ) {   // file exists (on the right folder)
          $delete_old = true;
          $del = strtolower($_GET['del']);    // old image-file to delete (format: int _ HEX{5} . jpg)
  }
  else {
      $delete_old = false;
  }

  // Calculate file-names, file-extensions, paths etc.
  // ---------------------------------------------------------------------------
  $rnd = substr(strtolower(md5(time())),0,5) .".";
  $ext = strtolower(end(explode(".", $_FILES["fileToUpload"]["name"])));

  $localFN = $id ."_". $rnd.$ext;       // local filename (new uploaded image)
  $thumbFN = "pi". $localFN;            // thumbnail (pico image)
  $path_file  = UPLOAD_DIR . $sub_dir . $localFN;   // target path + filename
  $path_thumb = UPLOAD_DIR . $sub_dir . $thumbFN;   // thumbnail path + filename

  $uploadOk = 1;                        // flag to catch uploading errors


  // TODO:
  // If is 'second' image, check that 1st image exists
  // --- Depricated:
  // Can be handled in presentation;
  // if 1st image is absend, then the second is used instead


  // Check common errors; then upload image if everything is ok
  //////////////////////////////////////////////////////////////////////////////

  // Check if image file is a actual image or fake image
  // ---------------------------------------------------------------------------
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if ($check !== false) {
      // File is an image
      $uploadOk = 1;
  }
  else {
      // File is not an image
      $uploadOk = -1;
      echo '{"success": false, "err" : "MIME ERROR"}'; die();
  }

  // Check if file already exists
  // if (file_exists($path_file)) {
  //    unlink($path_file);    // delete it if exists
  // }

  // Check file size
  // ---------------------------------------------------------------------------
  if ($_FILES["fileToUpload"]["size"] > 1048576) {    // limit filesize to 1MB
      $uploadOk = -2;
      echo '{"success": false, "err" : "SIZE ERROR"}'; die();
  }

  // Allow certain file formats (only jpeg)
  // ---------------------------------------------------------------------------
  if ($ext != "jpg" && $ext != "jpeg" ) {    // file extension shall be [ jpg | jpeg ]
      $uploadOk = -3;
      echo '{"success": false, "err" : "JPEG ERROR"}'; die();
  }
  // Check if $uploadOk is set to 0 by an error
  // (though this would have ended the script already) -------------------------
  if ($uploadOk < 0) {
      echo '{"success": false, "err" : "IMG-ERR:'. (-$uploadOk) .'"}'; die();

  }
  // if everything is ok, try to upload the file info folder
  // ---------------------------------------------------------------------------
  else {

      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $path_file)) {
          // image uploaded;

          // delete old image + old thumbnail
          //////////////////////////////////////////////////////////////////////
          if ($delete_old) {
              unlink(UPLOAD_DIR. $sub_dir . $del);        // delete old image
              unlink(UPLOAD_DIR. $sub_dir .'pi'. $del);   // delete old thumbnail
          }

          // Create thumbnail
          //////////////////////////////////////////////////////////////////////

          // load image and get image size
          $img = imagecreatefromjpeg( $path_file );
          $width = imagesx( $img );
          $height = imagesy( $img );

          // calculate thumbnail size
          $new_width = THUMBWIDTH;
          $new_height = floor( $height * ( THUMBWIDTH / $width ) );

          // create a new temporary image
          $tmp_img = imagecreatetruecolor( $new_width, $new_height );

          // copy and resize old image into new image
          imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

          // save thumbnail into a file
          imagejpeg( $tmp_img, $path_thumb );


          // Update item record on database
          //////////////////////////////////////////////////////////////////////

          // init database connection
          $_dbc = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DBMS);
          if ($_dbc->connect_errno) {
            echo "Database connection failed; Please try in a few minutes.";
            if (TESTING) echo $_dbc->connect_error;
            $_dbc->close(); die();
          }
          $_dbc->set_charset("utf8");

          if (IS_2ND_IMG)
            $_upd = $_dbc->prepare("UPDATE items SET img2 = ? WHERE id = ?");
          else
            $_upd = $_dbc->prepare("UPDATE items SET img = ? WHERE id = ?");
          $_upd->bind_param("sd", $localFN, $id);
          $_upd->execute();
          $_upd->close();
          $_dbc->close();



          // send image thumbnail for preview
          // -------------------------------------------------------------------

          echo '{ "success" : true, "img" : "'. $localFN .'", "sec" : "'. (IS_2ND_IMG ? 'true' : 'false') .'", "thumbnail" : "'. $path_thumb .'" }';
          die();    // everything done!

      }
      else {
          echo '{"success": false, "err" : "UPLOAD ERR"}'; die();
      }
  }