summaryrefslogtreecommitdiff
path: root/includes/upload_inc.php
blob: c694117a9a8fd47b7e57cfea4a5001f7afd2bf7a (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php
/**
 * @package fisheye
 * @subpackage functions
 */

use Bitweaver\Fisheye\FisheyeImage;
use Bitweaver\Fisheye\FisheyeGallery;
use Bitweaver\BitBase;
use Bitweaver\KernelTools;

/**
 * fisheye_handle_upload
 */
function fisheye_handle_upload( &$pFiles ) {
	global $gBitUser, $gContent, $gBitSystem, $fisheyeErrors, $fisheyeWarnings, $fisheyeSuccess, $gFisheyeUploads;

	// first of all set the execution time for this process to unlimited
	set_time_limit(0);

	$upImages = [];
	$upArchives = [];
	$upErrors = [];
	$upData = [];

	$i = 0;
	usort( $pFiles, 'fisheye_sort_uploads' );

	// No gallery was specified, let's try to find one or create one.
	if( empty( $_REQUEST['gallery_additions'] ) ) {
		if( $gBitUser->hasPermission( 'p_fisheye_create' )) {
			$_REQUEST['gallery_additions'] = [ fisheye_get_default_gallery_id( $gBitUser->mUserId, $gBitUser->getDisplayName()."'s Gallery" ) ];
		} else {
			$gBitSystem->fatalError( KernelTools::tra( "You don't have permissions to create a new gallery. Please select an existing one to insert your images to." ));
		}
	}

	foreach( array_keys( $pFiles ) as $key ) {
		if ( !empty($pFiles[$key]['name']) ) {
			$pFiles[$key]['type'] = $gBitSystem->verifyMimeType( $pFiles[$key]['tmp_name'] );
			if( preg_match( '/(^image|pdf|vnd)/i', $pFiles[$key]['type'] ?? '' ) ) {
				$upImages[$key] = $pFiles[$key];
				// clone the request data so edit service values are passed into store process
				$upData[$key] = $_REQUEST;
				// add the form data for each upload
				if( !empty( $_REQUEST['imagedata'][$i] ) ) {
					array_merge( $upData[$key], $_REQUEST['imagedata'][$i] );
				}
			} elseif( !empty( $pFiles[$key]['tmp_name'] ) && !empty( $pFiles[$key]['name'] ) ) {
				$upArchives[$key] = $pFiles[$key];
			}
			$i++;
		}
	}

	foreach( array_keys( $upArchives ) as $key ) {
		$upErrors = fisheye_process_archive( $upArchives[$key], $gContent, true );
	}

	foreach( array_keys( $upImages ) as $key ) {
		// resize original if we the user requests it
		if( !empty( $_REQUEST['resize'] ) ) {
			$upImages[$key]['resize'] = $_REQUEST['resize'];
		}
		$upErrors = array_merge( $upErrors, fisheye_store_upload( $upImages[$key], $upData[$key], !empty( $_REQUEST['rotate_image'] )));
	}

	if( !is_object( $gContent ) || !$gContent->isValid() ) {
		$gContent = new FisheyeGallery( $_REQUEST['gallery_additions'][0] );
		$gContent->load();
	}

	if( !empty( $gFisheyeUploads ) ){
		$_REQUEST['uploaded_objects'] = &$gFisheyeUploads;
		$gContent->invokeServices( "content_post_upload_function", $_REQUEST );
	}

	return $upErrors;
}

/**
 * fisheye_sort_upload
 */
function fisheye_sort_uploads( $a, $b ) {
	return strnatcmp( $a['name'], $b['name'] );
}

/**
 * fisheye_get_default_gallery_id
 */
function fisheye_get_default_gallery_id( $pUserId, $pNewName ) {
	global $gBitUser;
	$gal = new FisheyeGallery();
	$getHash = [ 'user_id' => $pUserId, 'max_records' => 1, 'sort_mode' => 'created_desc', 'show_empty' => true ];
	$upList = $gal->getList( $getHash );
	if( !empty( $upList ) ) {
		$ret = key( $upList );
	} else {
		$galleryHash = [ 'title' => $pNewName ];
		if( $gal->store( $galleryHash ) ) {
			$ret = $gal->mGalleryId;
		}
	}

	global $gContent;
	if( $ret && (!is_object( $gContent ) || !$gContent->isValid()) ) {
		$gContent = new FisheyeGallery( $ret );
		$gContent->load();
	}
	return $ret;
}

/**
 * fisheye_store_upload
 */
function fisheye_store_upload( &$pFileHash, $pImageData = [], $pAutoRotate=true ) {
	global $gBitSystem, $gFisheyeUploads;
	$ret = [];

	// verifyMimeType to make sure we are working with the proper file type assumptions
	$pFileHash['type'] = $gBitSystem->verifyMimeType($pFileHash['tmp_name']);
	if( !empty( $pFileHash ) && ( $pFileHash['size'] > 0 ) && is_file( $pFileHash['tmp_name'] ) && fisheye_verify_upload_item(  $pFileHash ) ) {
		// make a copy for each image we need to store
		$image = new FisheyeImage();
		// Inherit protector role from the target gallery if not explicitly set
		if( !isset( $pImageData['protector']['role_id'] ) && !empty( $pImageData['gallery_additions'] ) ) {
			$parentGalleryId = reset( $pImageData['gallery_additions'] );
			if( $parentContentId = $image->mDb->GetOne( "SELECT `content_id` FROM `".BIT_DB_PREFIX."fisheye_gallery` WHERE `gallery_id`=?", [ $parentGalleryId ] ) ) {
				if( ( $parentRole = $image->mDb->GetOne( "SELECT `role_id` FROM `".BIT_DB_PREFIX."liberty_content_role_map` WHERE `content_id`=?", [ $parentContentId ] ) ) !== false ) {
					$pImageData['protector']['role_id'] = $parentRole;
				}
			}
		}
		// Store/Update the image
		$pImageData['_files_override'] = [ $pFileHash ];
		$pImageData['process_storage'] = STORAGE_IMAGE;
		$pImageData['purge_from_galleries'] = true;
		// store the image
		if( !$image->store( $pImageData ) ) {
			$ret = $image->mErrors;
		} else {
			$pFileHash['content_id'] = $image->getField( 'content_id' );
			$pFileHash['image_id'] = $image->getField( 'image_id' );
			$image->load();
			// play with image some more if user has requested it
			if( $pAutoRotate ) {
				$image->rotateImage( 'auto' );
			}
			if( !($galleryAdditions = BitBase::getParameter( $pImageData, 'gallery_additions' )) ) {
				global $gBitUser;
				$galleryAdditions = [ fisheye_get_default_gallery_id( $gBitUser->mUserId, $gBitUser->getDisplayName()."'s Gallery" ) ];
			}
			$image->addToGalleries( $galleryAdditions );
			$gFisheyeUploads[] = $image;
		}

		// when we're using xupload, we need to remove temp files manually
		if ( is_readable( $pFileHash['tmp_name'] ) ) @unlink( $pFileHash['tmp_name'] );
	}
	return $ret;
}

/**
 * Recursively builds a tree where each directory represents a gallery, and files are assumed to be images.
 */
function fisheye_process_archive( &$pFileHash, &$pParentGallery, $pRoot=false ) {
	global $gBitSystem, $gBitUser;
	$errors = [];

	if( ( $destDir = \Bitweaver\Liberty\liberty_process_archive( $pFileHash ) ) && ( !empty( $_REQUEST['process_archive'] ) || !$gBitUser->hasPermission( 'p_fisheye_upload_nonimages' ) ) ) {
		if( empty( $pParentGallery ) && !is_file( $pFileHash['tmp_name'] ) ) {
			$pParentGallery = new FisheyeGallery();
			$galleryHash = [ 'title' => basename( $destDir ) ];
			if( !$pParentGallery->store( $galleryHash ) ) {
				$errors = array_merge( $errors, array_values( $pParentGallery->mErrors ) );
			}
			global $gContent;
			$gContent = &$pParentGallery;
		}

		if( !empty( $pParentGallery ) ) {
			$pFileHash['gallery_id'] = $pParentGallery->getField( 'gallery_id' );
		}
		fisheye_process_directory( $destDir, $pParentGallery, $pRoot );
	} else {
		global $gBitUser;
		if( $gBitUser->hasPermission( 'p_fisheye_upload_nonimages' ) ) {
			$errors = array_merge( $errors, fisheye_store_upload( $pFileHash ));
		} else {
			$errors['upload'] = KernelTools::tra( 'Your upload could not be processed because it was determined to be a non-image and you only have permission to upload images.' );
		}
	}
	return $errors;
}

if( !function_exists( 'fisheye_verify_upload_item' ) ) {
// Possible override
function fisheye_verify_upload_item( $pScanFile ) {
	global $gBitUser;
	return $gBitUser->hasPermission( 'p_fisheye_upload_nonimages' ) || preg_match( '/^video\/*/', $pScanFile['type'] ) || preg_match( '/^image\/*/', $pScanFile['type'] ) || preg_match( '/pdf/i', $pScanFile['type'] );
}
}

/**
 * Recursively builds a tree where each directory represents a gallery, and files are assumed to be images.
 */
function fisheye_process_directory( $pDestinationDir, &$pParentGallery, $pRoot=false ) {
	global $gBitSystem, $gBitUser;
	$errors = [];
	if( $archiveDir = opendir( $pDestinationDir ) ) {
		$order = 100;
		while( $fileName = readdir($archiveDir) ) {
			$sortedNames[] = $fileName;
		}
		sort( $sortedNames );
		foreach( $sortedNames as $fileName ) {
			if( $fileName == 'Thumbs.db' ) {
				unlink( "$pDestinationDir/$fileName" );
			}
			if( !preg_match( '/^\./', $fileName ) && ( $fileName != 'Thumbs.db' ) ) {
				$mimeResults = $gBitSystem->verifyFileExtension( $pDestinationDir.'/'.$fileName );
				$scanFile = [
					'type' => $mimeResults[1],
					'name' => $fileName,
					'size' => filesize( "$pDestinationDir/$fileName" ),
					'tmp_name' => "$pDestinationDir/$fileName",
				];

				if( !empty( $_REQUEST['resize'] ) && is_numeric( $_REQUEST['resize'] ) ) {
					$scanFile['max_height'] = $scanFile['max_width'] = $_REQUEST['resize'];
				}

				if( is_dir( $pDestinationDir.'/'.$fileName ) ) {
					if( $fileName == '__MACOSX' ) {
						// Mac OS resources file
						KernelTools::unlink_r( $pDestinationDir.'/'.$fileName );
					} else {
						// We found a new Gallery!
						$newGallery = new FisheyeGallery();
						$galleryHash = [ 'title' => str_replace( '_', ' ', $fileName ) ];
						if( $newGallery->store( $galleryHash ) ) {
							if( $pRoot ) {
								$newGallery->addToGalleries( $_REQUEST['gallery_additions'] );
							}
							if( is_object( $pParentGallery ) ) {
								$pParentGallery->addItem( $newGallery->mContentId, $order );
							}
							//recurse down in!
							$errors = array_merge( $errors, fisheye_process_archive( $scanFile, $newGallery ) );
						} else {
							$errors = array_merge( $errors, array_values( $newGallery->mErrors ) );
						}
					}
				} elseif( preg_match( '/.+\/*zip*/', $scanFile['type'] ) ) {
					//recurse down in!
					$errors = array_merge( $errors, fisheye_process_archive( $scanFile, $pParentGallery ) );
				} elseif( fisheye_verify_upload_item( $scanFile ) ) {
					$newImage = new FisheyeImage();
					$imageHash = [ '_files_override' => [ $scanFile ] ];
					if( $newImage->store( $imageHash ) ) {
						if( $pRoot ) {
							$newImage->addToGalleries( $_REQUEST['gallery_additions'] );
						}
						if( !is_object( $pParentGallery ) ) {
							global $gBitUser;
							$pParentGallery = new FisheyeGallery( fisheye_get_default_gallery_id( $gBitUser->mUserId, $gBitUser->getDisplayName()."'s Gallery" ) );
							$pParentGallery->load();
						}
						$pParentGallery->addItem( $newImage->mContentId );
					} else {
						$errors = array_merge( $errors, array_values( $newImage->mErrors ) );
					}
				} elseif( is_file( $scanFile['tmp_name'] ) ) {
					// unknown file type, let's be tidy and clean it up
					unlink( $scanFile['tmp_name'] );
				}
				$order += 10;
			}
		}
		if ( !KernelTools::is_windows() ) {
			KernelTools::unlink_r( $pDestinationDir );
		}
	}
	return $errors;
}

// this function will process a directory and all it's sub directories without
// making any assumptions. hierarchy of sub directories is maintained and
// archives can be processed or simply added to the galleries.
function fisheye_process_ftp_directory( $pProcessDir ) {
	global $gBitSystem, $gBitUser;
	if( empty( $_REQUEST['gallery_additions'] ) ) {
		$_REQUEST['gallery_additions'] = [];
	}

	$errors = [];
	if( $archiveDir = opendir( $pProcessDir ) ) {
		$order = 100;
		while( $fileName = readdir($archiveDir) ) {
			$sortedNames[] = $fileName;
		}

		sort( $sortedNames );
		$order = 100;

		foreach( $sortedNames as $fileName ) {
			if( !preg_match( '/^\./', $fileName ) && ( $fileName != 'Thumbs.db' ) ) {
				$scanFile = [
					'type'     => $gBitSystem->lookupMimeType( substr( $fileName, strrpos( $fileName, '.' ) + 1 )  ),
					'name'     => $fileName,
					'size'     => filesize( "$pProcessDir/$fileName" ),
					'tmp_name' => "$pProcessDir/$fileName",
				];

				if( is_dir( $pProcessDir.'/'.$fileName ) ) {
					// create a new gallery from directory
					$dirGallery = new FisheyeGallery();
					$galleryHash = [ 'title' => str_replace( '_', ' ', $fileName ) ];
					if( $dirGallery->store( $galleryHash ) ) {
						$dirGallery->addToGalleries( $_REQUEST['gallery_additions'] );
						$errors = array_merge( $errors, fisheye_process_directory( $pProcessDir.'/'.$fileName, $dirGallery ) );
					} else {
						$errors = array_merge( $errors, array_values( $dirGallery->mErrors ) );
					}
					unset( $dirGallery );
				} else {
					if( preg_match( '/(^image|pdf)/i', $scanFile['type'] ) ) {
						// process image
						$newImage = new FisheyeImage();
						$imageHash = [ 'upload' => $scanFile ];
						if( $newImage->store( $imageHash ) ) {
							$newImage->addToGalleries( $_REQUEST['gallery_additions'] );

							// if we have a gallery to add these images to, load one of them
							if( !empty( $_REQUEST['gallery_additions'][0] ) && @!is_object( $imageGallery ) ) {
								$imageGallery = new FisheyeGallery();
								$imageGallery->mGalleryId = $_REQUEST['gallery_additions'][0];
								$imageGallery->load();
							}

							if( @!is_object( $imageGallery ) ) {
								global $gBitUser;
								$galleryHash = [ 'title' => $gBitUser->getDisplayName()."'s Gallery" ];
								$imageGallery = new FisheyeGallery();
								if( $imageGallery->store( $galleryHash ) ) {
									$imageGallery->load();
								} else {
									$errors = array_merge( $errors, array_values( $imageGallery->mErrors ) );
								}
							}

							$imageGallery->addItem( $newImage->mContentId );
						} else {
							$errors = array_merge( $errors, array_values( $newImage->mErrors ) );
						}
					} else {
						// create a new gallery from archive
						$archiveGallery = new FisheyeGallery();
						$galleryHash = [ 'title' => substr( $fileName, 0, str_replace( '_', ' ', strrpos( $fileName, '.' ) ) ) ];
						if( !$archiveGallery->store( $galleryHash ) ) {
							$errors = array_merge( $errors, array_values( $archiveGallery->mErrors ) );
						}

						$errors = fisheye_process_archive( $scanFile, $archiveGallery, true );
						unset( $archiveGallery );
					}
				}
				$order += 10;
			}
		}
	}
	return $errors;
}