summaryrefslogtreecommitdiff
path: root/includes/classes/FisheyeRemote.php
blob: 9eee1509e1402ebc735e9f5a6d37418f5f8d3d89 (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
<?php
/**
 * Gallery2 Remote support for fisheye
 *
 * @package  fisheye
 * @version  $Header$
 * @author   spider <spider@steelsun.com>
 * @author   tylerbello <tylerbello@gmail.com>
 */

// +----------------------------------------------------------------------+
// | Copyright (c) 2004, bitweaver.org
// +----------------------------------------------------------------------+
// | All Rights Reserved. See below for details and a complete list of authors.
// | Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See http://www.gnu.org/copyleft/lesser.html for details
// |
// | For comments, please use phpdocu.sourceforge.net documentation standards!!!
// | -> see http://phpdocu.sourceforge.net/
// +----------------------------------------------------------------------+
// | Authors: spider <spider@steelsun.com>
// +----------------------------------------------------------------------+

/**
 * required setup
 */
namespace Bitweaver\Fisheye;

use Bitweaver\KernelTools;

define( 'FEG2REMOTE_SUCCESS', 0 );

define( 'FEG2REMOTE_PROTOCOL_MAJOR_VERSION_INVALID', 101 );
define( 'FEG2REMOTE_PROTOCOL_MINOR_VERSION_INVALID', 102 );
define( 'FEG2REMOTE_PROTOCOL_VERSION_FORMAT_INVALID', 103 );
define( 'FEG2REMOTE_PROTOCOL_VERSION_MISSING', 104 );

define( 'FEG2REMOTE_PASSWORD_WRONG', 201 );
define( 'FEG2REMOTE_LOGIN_MISSING', 202 );

define( 'FEG2REMOTE_UNKNOWN_COMMAND', 301 );
define( 'FEG2REMOTE_MISSING_ARGUMENTS', 302 );

define( 'FEG2REMOTE_NO_ADD_PERMISSION', 401 );
define( 'FEG2REMOTE_NO_FILENAME', 402 );
define( 'FEG2REMOTE_UPLOAD_PHOTO_FAIL', 403 );
define( 'FEG2REMOTE_NO_WRITE_PERMISSION', 404 );
define( 'FEG2REMOTE_NO_VIEW PERMISSION', 405 );

define( 'FEG2REMOTE_NO_CREATE_ALBUM_PERMISSION', 501 );
define( 'FEG2REMOTE_CREATE_ALBUM_FAILED', 502 );
define( 'FEG2REMOTE_MOVE_ALBUM_FAILED', 503 );
define( 'FEG2REMOTE_ROTATE_IMAGE_FAILED', 504 );

/**
 * @package  fisheye
 */
class FisheyeRemote {

	public $mResponse = [];

	public $mSubGalIdx = 1;

	public function getApiVersion() {
		return '2.14';
	}

	// separate out pPostData and pParamhash data since some plugins can populate _POST['g2_form'] and _GET['g2_form'] differently.
	// weird but true. ubermind is an example
	public function processRequest( $pGetData, $pPostData ) {
		$pData = array_merge($pGetData, $pPostData); //Some programs (galleryexport) pass both post and get...and the cmd can be in either get or post

		if(!empty($pData)){
			switch ($pData['cmd']) {
				case 'login':
					$response = $this->cmdLogin( $pPostData );
					break;

				case 'fetch-albums':
					$response = $this->cmdFetchAlbums( $pPostData );
					break;

				case 'fetch-albums-prune':
					$response = $this->cmdFetchAlbums( $pPostData );
					break;

				case 'add-item':
					$response = $this->cmdAddItem( $pPostData );
					break;

				case 'album-properties':
					// not implemented yet
					break;

				case 'new-album':
					$response = $this->cmdNewAlbum( $pPostData );
					break;

				case 'fetch-album-images':
					// not implemented yet
					break;

				case 'move-album':
					// not implemented yet
					break;

				case 'increment-view-count':
					// not implemented yet
					break;

				case 'image-properties':
					// not implemented yet
					break;

				case 'no-op':
					$response = $this->cmdNoOp( $pPostData );
					// not implemented yet
					break;

				default:
					$response = $this->createResponse( FEG2REMOTE_UNKNOWN_COMMAND, "Command unknown: ".$pGetData['cmd'] );
					break;
			}
		} else {
			$response = $this->createResponse( FEG2REMOTE_UNKNOWN_COMMAND, "No command received." );
		}

		if( !empty( $response ) ) {
			print $this->sendResponse( $response );
		}
	}

	public function cmdNoOp( $pParamHash ) {
		global $gBitUser;

		$response = $this->createResponse( FEG2REMOTE_SUCCESS, 'No-op successful' );
		return $response;
	}

	public function cmdLogin( $pParamHash ) {
		global $gBitUser, $gBitSystem;
		$url = $gBitUser->login( $pParamHash['uname'], $pParamHash['password'] );
		$response = $gBitUser->isRegistered()
			/*
			$cookieTime =  ( int )( time() + $gBitSystem->getConfig( 'users_remember_time', 86400 ));
			$cookiePath = $gBitSystem->getConfig( 'cookie_path', BIT_ROOT_URL );
			$cookieDomain = $gBitSystem->getConfig( 'cookie_domain', "" );
			setcookie( 'GALLERYSID', session_id(), $cookieTime, $cookiePath, $cookieDomain );
			*/
			? $this->createResponse( FEG2REMOTE_SUCCESS, 'Login successful.', [ 'server_version' => $this->getApiVersion() ] )
			: $this->createResponse( FEG2REMOTE_PASSWORD_WRONG, 'Invalid username or password' );

		return $response;
	}

	// Recursively traverses a multi-dimensional array of galleries
	public function traverseGalleries( &$pGalHash, &$pResponse ) {
		global $gBitUser;

		// Albums don't like being 0 indexed
		$this->mSubGalIdx = 0;

		// the lightroom client is dumb, and can only handle one 0 level parent
		if( stripos( $_SERVER['HTTP_USER_AGENT'], 'lightroom' ) !== false ) {
			$this->mSubGalIdx++;
			$pResponse['album.parent.' . $this->mSubGalIdx] = 0;
			$pResponse['album.name.' . $this->mSubGalIdx] = 1;
			$pResponse['album.title.' . $this->mSubGalIdx] = KernelTools::tra( 'Select a Gallery' );
			$pResponse['album.perms.add.' . $this->mSubGalIdx] = 'false';
			$pResponse['album.perms.write.' . $this->mSubGalIdx] = 'false';
			$pResponse['album.perms.del_alb.' . $this->mSubGalIdx] = 'false';
			$pResponse['album.perms.create_sub.' . $this->mSubGalIdx] = 'true';
		}

		return $this->traverseSubGalleries( $pGalHash, $pResponse, 1 );
	}

	/**
	* Function that returns link to display a piece of content
	* @param $pGalHash branch of gallery information from FisheyeGallery::getTree
	* @param $pResponse aggregate string containing response array
	* @param $pParentRandom depth of pGalHash - this is used to non-definitively uniquify album.parent and album.name entries
	* @return string the url to display the gallery.
	*/
	public function traverseSubGalleries( &$pGalHash, &$pResponse, $pParentRandom ) {
		global $gBitUser;
		foreach( $pGalHash as $key=>$gallery) {
			$this->mSubGalIdx++;

			// Any number greater than 2 digits crashes iPhoto2Gallery
			$randomizer = str_pad( rand( 1, 99 ), 2, '0' );
			$pResponse['album.parent.' . $this->mSubGalIdx] = $gallery['content']['level'] != 0
				// Fisheye allows directories to below to multiple parents - not in gallery. This confuses some clients
				// We pad with a random number for uniqueness
				? $gallery['content']['cb_gallery_content_id'].$pParentRandom
				// the lightroom client is dumb, and can only handle one 0 level parent
				: ( stripos( $_SERVER['HTTP_USER_AGENT'], 'lightroom' ) !== false ? 1 : 0);

			// append pParentRandom to make .name probably unique since Fisheye can handle one gallery linked to multiple parents
			$pResponse['album.name.' . $this->mSubGalIdx] = $gallery['content']['content_id'].$randomizer;
			$pResponse['album.title.' . $this->mSubGalIdx] = $this->cleanResponseValue( $gallery['content']['title'] );

			if( !empty( $gallery['content']['data'] ) ) {
				$pResponse['album.summary.' . $this->mSubGalIdx] = $gallery['content']['data'];
				$pResponse['album.info.extrafields.' . $this->mSubGalIdx] = "Summary";
			}

			$pResponse['album.perms.add.' . $this->mSubGalIdx] = 'true';
			$pResponse['album.perms.write.' . $this->mSubGalIdx] = 'true';
			$pResponse['album.perms.del_alb.' . $this->mSubGalIdx] = 'true';
			$pResponse['album.perms.create_sub.' . $this->mSubGalIdx] = 'true';

			if( !empty( $gallery['children'] ) ) {
				$this->traverseSubGalleries($gallery['children'],$pResponse, $randomizer );
			}
		}
		$ret = $this->mSubGalIdx;
		return $ret;
	}

	public function cmdFetchAlbums( $pParamHash ) {
		require_once FISHEYE_PKG_CLASS_PATH.'FisheyeGallery.php';
		global $gBitUser;
		if( $gBitUser->isRegistered() ) {
			$treeGallery = new FisheyeGallery();
			$listHash['user_id'] = $gBitUser->mUserId;
			if( $galleryList = $treeGallery->getTree( [ $listHash, 'name' => "gallery_id", 'id' => "gallerylist", 'item_attributes' => [ 'class'=>'listingtitle' ] ] ) ) {
				$galResponse = [];
				$galleryCount = $this->traverseGalleries( $galleryList, $galResponse );
				$galResponse['album_count'] = $galleryCount;
				$galResponse['can_create_root'] = 'true';
				$response = $this->createResponse( FEG2REMOTE_SUCCESS, 'Gallery list successful', $galResponse );
			} else {
				// perhaps we should make at least on gallery at this point?
				$response = $this->createResponse( FEG2REMOTE_SUCCESS, 'No galleries', [ 'album_count' => 0 ] );
			}
		} else {
			$response = $this->createResponse( FEG2REMOTE_PASSWORD_WRONG, 'Application not logged in' );
		}
		return $response;
	}

	public function cmdAddItem( $pParamHash ) {
		$response = [];

		$uploadFile =  !empty( $_FILES['g2_userfile'] ) ? $_FILES['g2_userfile'] : null;

		if( empty( $pParamHash['set_albumName'] ) ) {
			$response = $this->createResponse( FEG2REMOTE_CREATE_ALBUM_FAILED , 'No gallery specified' );
		} elseif( empty( $uploadFile ) || empty( $uploadFile['size'] ) ) {
			$response = $this->createResponse( FEG2REMOTE_NO_FILENAME, 'No image uploaded' );
		} else {
			$storeHash['title'] = !empty( $pParamHash['force_filename'] ) ? $pParamHash['force_filename'] : null;
			$storeHash['summary'] = !empty( $pParamHash['extrafield.Summary'] ) ? $pParamHash['extrafield.Summary'] : null;
			$storeHash['edit'] = !empty( $pParamHash['extrafield.Description'] ) ? $pParamHash['extrafield.Description'] : null;

			require_once FISHEYE_PKG_INCLUDE_PATH.'upload_inc.php';

			$parentGallery = new FisheyeGallery();
			if( $parentGallery = $parentGallery->lookup([ 'content_id' => $pParamHash['set_albumName'] ] ) ) {
				$parentGallery->load();
				$storeHash['gallery_additions'] = [ $parentGallery->mGalleryId ];
			}
			$response = $errors = fisheye_store_upload( $uploadFile , $storeHash )
				? $response = $this->createResponse( FEG2REMOTE_UPLOAD_PHOTO_FAIL, 'Export Failed' )
				: $this->createResponse( FEG2REMOTE_SUCCESS, 'Image added', [ 'item_name'=>$uploadFile['name'] ] );
		}

		return $response;
	}

	public function cmdNewAlbum( $pParamHash ) {
		global $gBitUser;
		$response = [];

		if( empty( $pParamHash['newAlbumTitle'] ) ) {
			$pParamHash['newAlbumTitle'] = $gBitUser->getTitle()."'s Gallery";
		}

		$storeHash['title'] = !empty($pParamHash['newAlbumTitle']) ? $pParamHash['newAlbumTitle'] : '';
		$storeHash['edit']  = !empty($pParamHash['newAlbumDesc'])  ? $pParamHash['newAlbumDesc']  : '';
		$gallery = new FisheyeGallery();
		$gallery->store( $storeHash );

		if($pParamHash['set_albumName']){
			$parentGallery = new FisheyeGallery();
			if( $parentGallery = $parentGallery->lookup(['content_id' => $pParamHash['set_albumName'] ] ) ) {
				$parentGallery->load();
				$gallery->addToGalleries([ $parentGallery->mGalleryId ] );
			}
		}

		$response = $this->createResponse( FEG2REMOTE_SUCCESS, 'Gallery created', [ 'album_name' => $storeHash['title'] ] );

		return $response;
	}

	public function sendResponse( $pResponse ) {
		global $gBitUser;
		print "#__GR2PROTO__\n";
//error_log( "#__GR2PROTO__".' : '.$gBitUser->mUserId );
		foreach ($pResponse as $k => $value) {
			print  "$k=$value\n";
//error_log( "$k=$value" );
		}
		// must be last
		print "auth_token=".$gBitUser->mTicket;
//error_log( "auth_token=".$gBitUser->mTicket );
//error_log( "#__end__" );
	}

	public function createResponse( $pStatus, $pStatusText, $pExtra = null ) {
		$ret = [];

		// Each response must contain at least the keys: status and status_text.
		$ret['status'] = $this->cleanResponseValue( $pStatus );
		// translate the text response for i18n
		$ret['status_text'] = $this->cleanResponseValue( KernelTools::tra( $pStatusText ) );
		// tack on any additional responses
		if( !empty( $pExtra ) && is_array( $pExtra ) ) {
			foreach( $pExtra as $k => $value ) {
				$ret[$this->cleanResponseKey( $k )] = $this->cleanResponseValue( $value );
			}
		}
		return $ret;
	}

	/**
	 * This will clean up the response value to make sure it is in an acceptable format for the remote client.
	 * Gallery apparently is very particular about the manner in which this data is cleaned up, and must be done
	 * in this specific order.
	 */
	public function cleanResponseValue( $pValue ) {
		$pValue = str_replace('\\', '\\\\', $pValue);
		$pValue = str_replace("\r\n", '\n', $pValue);
		$pValue = str_replace([ "\r", "\n", "\t" ], [ '\n', '\n', '\t' ], $pValue);
		$pValue = str_replace([ '#', '!', '=' ], [ '\\#', '\\!', '\\=' ], $pValue);
		return $pValue;
	}

	public function cleanResponseKey( $pKey ) {
		return str_replace([ '#', '!', '=', ':' ], [ '\\#', '\\!', '\\=', '\\:' ], $pKey);
	}

}