This repository was archived by the owner on Apr 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathindex.php
341 lines (253 loc) · 8.24 KB
/
index.php
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
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';
$app = new Silex\Application(['debug' => true]);
/***
*
* Let's configure the database we'll use through Mongovel
*
*/
$container = new Illuminate\Container\Container;
$container->singleton('mongoveldb', function() {
$d = new Mongovel\DB('mongodb://localhost', 'circular', [
'host' => 'localhost',
'port' => 27017,
]);
unset($d->options['server']);
return $d;
});
class Config {
public function get($s) {
return false;
}
}
$container->singleton('config', function() {
return new Config;
});
Mongovel\Mongovel::setContainer($container);
/***
*
* Let's group controllers on whether they're `public` or `protected`
*
*/
$public = $app['controllers_factory'];
$protected = $app['controllers_factory'];
/***
*
* Auth.
*
* Sample output:
* array (
* 'id' => '507ed38198dee47b47000001',
* 'users' => array (
* '507ed38198dee47b47000000' => MongoId('507ed38198dee47b47000000'),
* '507ed31498dee4ce42000002' => MongoId('507ed31498dee4ce42000002'),
* ))
*
*/
$protected->before(function (Request $request) use ($app) {
// `Protected` endpoints require authentication:
(new CustomSessionHandler)->setup();
if (!isset($_SESSION['account'])) {
return new Response('Unauthorized', 401);
}
// All right, our user is authenticated.
$users = array();
foreach ($_SESSION['account']['users'] as $id => $value) {
$users[$id] = new MongoId($id);
}
$app['account'] = [
'id' => $_SESSION['account']['id'],
'users' => $users,
];
});
/***
*
* Accepting JSON in request body.
* @note: the method described in http://silex.sensiolabs.org/doc/cookbook/json_request_body.html doesn't allow us to get the whole parameter array.
*
*/
$app->before(function (Request $request) use ($app) {
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$app['data'] = json_decode($request->getContent(), true);
}
});
/***
*
* The `/posts` endpoint conforms to Backbone.sync's default CRUD/REST implementation.
* @see http://backbonejs.org/#Sync
*
*/
$protected->get('/api/posts', function () use ($app) {
// Retrieve all posts by users managed by current account, sorted by time ascending:
$posts = Post::find(array('user._id' => array('$in' => array_values($app['account']['users']))))
->sort(array('time' => 1));
$out = array();
foreach ($posts as $post) {
// Don't expose authentication info through the API, only the user ID:
$post->user = (string) $post->user['_id'];
// Don't display Twitter request info either:
unset($post->type);
$post->status = $post->params['status'];
unset($post->params);
// Translation layer/adapter for Backbone:
// XXX: Use the exact same data in Backbone as in Mongo
// @see http://stackoverflow.com/questions/12390553/how-to-make-backbones-and-mongodbs-ids-work-seamlessly
//
// This is now done in Mongovel:
$out[] = $post->toArray();
}
return $app->json($out);
});
$protected->post('/api/posts', function (Request $request) use ($app) {
$post = $app['data'];
// Check that this account really manages this user
if (!array_key_exists($post['user'], $app['account']['users'])) {
return new Response('Unauthorized', 401);
}
// Add user information:
$m = new MongoClient();
$user = $m->circular->users->findOne(array('_id' => new MongoId($post['user'])));
$post['user'] = $user;
// Add Twitter request info:
if (isset($post['picture'])) {
$post['type'] = 'post_with_media';
}
else {
$post['type'] = 'post';
}
// Nest status into `params`:
$post['params'] = array('status' => $post['status']);
unset($post['status']);
// XXX: Apparently Backbone has poor support for nested attributes
// @see http://stackoverflow.com/questions/6351271/backbone-js-get-and-set-nested-object-attribute
$m = new MongoClient();
if (isset($post['time']) && $post['time'] == "now") {
// If explicitly requested, send it right now through `queue`:
$m->circular->queue->insert($post);
}
else {
$m->circular->posts->insert($post);
}
// MongoId are assumed to be unique accross collections
// @see http://stackoverflow.com/questions/5303869/mongodb-are-mongoids-unique-across-collections
return $app->json(array('id' => (string) $post['_id']));
});
$protected->delete('/api/posts/{id}', function (Request $request, $id) use ($app) {
// According to the assert, this looks like a valid MongoId
$m = new MongoClient();
$m->circular->posts->remove(array(
'_id' => new MongoId($id),
'user._id' => array('$in' => array_values($app['account']['users']))
));
// We only delete the post if it is owned by the current user.
return new Response('Deleted', 204);
})
->assert('id', '\w{24}');
$protected->put('/api/posts/{id}', function (Request $request, $id) use ($app) {
$put = $app['data'];
// The only possible update right now is clicking "Post now" on a scheduled post:
if (isset($put['time']) && $put['time'] == "now") {
$m = new MongoClient();
$post = $m->circular->posts->findOne(array(
'_id' => new MongoId($id),
'user._id' => array('$in' => array_values($app['account']['users']))
));
// We only update the post if it is owned by the current user.
if ($post) {
// Move to sending queue:
$m->circular->queue->insert($post);
$m->circular->posts->remove(array('_id' => $post['_id']));
}
}
return $app->json(["success" => true]);
})
->assert('id', '\w{24}');
/***
*
* The `/times` endpoint enables bulk modifications of posts' times via POST.
*
*/
$protected->post('/api/times', function (Request $request) use ($app) {
$posts = $app['data']['posts'];
$m = new MongoClient();
$mongoposts = $m->circular->posts;
foreach ($posts as $post) {
$mongoposts->update(
array(
'_id' => new MongoId($post['id']),
'user._id' => array('$in' => array_values($app['account']['users']))
),
array('$set' => array('time' => new MongoDate($post['time'])))
);
// We only update the post if it is owned by the current user.
}
return $app->json(["success" => true]);
});
/***
*
* The `/upload` endpoint enables image uploading and creates a square 100x100px thumbnail.
*
*/
$protected->post('/api/upload', function (Request $request) use ($app) {
$file = $request->files->get('userfile');
if ($file->isValid()) {
$extension = $file->guessExtension();
// Use MD5 to prevent collision between different pictures:
$md5 = md5_file($file->getRealPath());
$filename = 'uploads/' . $app['account']['id'] . '/' . $md5 . '.' . $extension;
$thumbnailname = 'uploads/' . $app['account']['id'] . '/' . $md5 . '.100x100' . '.' . $extension;
$file = $file->move(__DIR__.'/../uploads/'.$app['account']['id'], $md5.'.'.$extension);
// Create thumbnail:
$simpleResize = new SimpleResize($file->getRealPath());
$simpleResize->resizeImage(100, 100, 'crop');
$simpleResize->saveImage(__DIR__.'/../'.$thumbnailname, 100);
return $app->json(array('url' => APP_URL.$filename, 'thumbnail' => APP_URL.$thumbnailname));
}
});
/***
*
* The `/settings` endpoint lets users interact with server-stored account-wide settings (for now, email).
*
*/
$protected->get('/api/settings', function (Request $request) use ($app) {
$account = Account::findOne(array('_id' => new MongoId($app['account']['id'])));
unset($account->users);
return $app->json($account->toArray());
});
$protected->post('/api/settings', function (Request $request) use ($app) {
$email = $app['data']['email'];
$m = new MongoClient();
if ($email) {
$m->circular->accounts->update(
array('_id' => new MongoId($app['account']['id'])),
array('$set' => array('email' => $email))
);
}
else {
$m->circular->accounts->update(
array('_id' => new MongoId($app['account']['id'])),
array('$unset' => array('email' => true))
);
}
return $app->json(["success" => true]);
});
/***
*
* The `/counter` public endpoint returns the number of scheduled posts queued right now.
*
*/
$public->get('/api/counter', function (Request $request) use ($app) {
$count = Post::count();
return $app->json(['count' => $count]);
});
/***
*
* Run, App, Run!
*
*/
$app->mount('/', $public);
$app->mount('/', $protected);
$app->run();