Pluf Framework

Pluf Framework Git Source Tree


Root/src/Pluf/Views.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
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# ***** END LICENSE BLOCK ***** */
 
Pluf::loadFunction('Pluf_HTTP_URL_urlForView');
Pluf::loadFunction('Pluf_Shortcuts_GetFormForModel');
Pluf::loadFunction('Pluf_Shortcuts_GetObjectOr404');
Pluf::loadFunction('Pluf_Shortcuts_RenderToResponse');
 
/**
 * Some basic views that can be reused by other views.
 *
 * Most of them are not supposed to be called directly via the
 * dispatcher as they take extra parameters for basic customization.
 */
class Pluf_Views
{
    /**
     * Log the user in.
     *
     * The login form is provided by the login_form.html template.
     * The '_redirect_after' hidden value is used to redirect the user
     * after successfull login. If the view is called with
     * _redirect_after set in the query as a GET variable it will be
     * available as $_redirect_after in the template.
     *
     * @param Request Request object
     * @param array Match
     * @param string Default redirect URL after login ('/')
     * @param array Extra context values (array()).
     * @param string Login form template ('login_form.html')
     * @return Response object
     */
    function login($request, $match, $success_url='/', $extra_context=array(),
                   $template='login_form.html')
    {
        if (!empty($request->REQUEST['_redirect_after'])) {
            $success_url = $request->REQUEST['_redirect_after'];
        }
        $error = '';
        if ($request->method == 'POST') {
            $users = new Pluf_User();
            if (false === ($user = $users->checkCreditentials($request->POST['login'], $request->POST['password']))) {
                $error = __('The login or the password is not valid. The login and the password are case sensitive.');
            } else {
                if (!$request->session->getTestCookie()) {
                    $error = __('You need to enable the cookies in your browser to access this website.');
                } else {
                    $request->user = $user;
                    $request->session->clear();
                    $request->session->setData('login_time', gmdate('Y-m-d H:i:s'));
                    $user->last_login = gmdate('Y-m-d H:i:s');
                    $user->update();
                    $request->session->deleteTestCookie();
                    return new Pluf_HTTP_Response_Redirect($success_url);
                }
            }
        }
        // Show the login form
        $request->session->createTestCookie();
        $context = new Pluf_Template_Context_Request($request,
                           array_merge(array(
                           'page_title' => __('Sign In'),
                           '_redirect_after' => $success_url,
                           'error' => $error), $extra_context));
        $tmpl = new Pluf_Template($template);
        return new Pluf_HTTP_Response($tmpl->render($context));
    }
 
    /**
     * Logout the user.
     *
     * The success url is either an absolute url starting with
     * http(s):// or considered as an action.
     *
     * @param Request Request object
     * @param array Match
     * @param string Default redirect URL after login '/'
     * @return Response object
     */
    function logout($request, $match, $success_url='/')
    {
        $request->user = new Pluf_User();
        $request->session->clear();
        $request->session->setData('logout_time', gmdate('Y-m-d H:i:s'));
        if (0 !== strpos($success_url, 'http')) {
            $murl = new Pluf_HTTP_URL();
            $success_url = Pluf::f('app_base').$murl->generate($success_url);
        }
        return new Pluf_HTTP_Response_Redirect($success_url);
    }
 
 
    /**
     * Create an object (Part of the CRUD series).
     *
     * The minimal extra parameter is the model class name. The list
     * of extra parameters is:
     *
     * 'model' - Class name string, required.
     *
     * 'extra_context' - Array of key/values to be added to the
     *                   context (array())
     *
     * 'extra_form' - Array of key/values to be added to the
     *                   form generation (array())
     *
     * 'login_required' - Do we require login (false)
     *
     * 'template' - Template to use ('"model class"_create_form.html')
     *
     * 'post_save_redirect' - View to redirect after saving (use
     *                        getAbsoluteUrl() method of the mode)
     *
     * 'post_save_redirect_keys' - Which keys of the model to pass to
     *                             the view (array('id'))
     *
     * @param Pluf_HTTP_Request Request object
     * @param array Match
     * @param array Extra parameters
     * @return Pluf_HTTP_Response Response object (can be a redirect)
     */
    public function createObject($request, $match, $p)
    {
        $default = array(
                         'extra_context' => array(),
                         'extra_form' => array(),
                         'login_required' => false,
                         );
        $p = array_merge($default, $p);
        if (isset($p['login_required']) && true == $p['login_required']) {
            if ($request->user->isAnonymous()) {
                return new Pluf_HTTP_Response_RedirectToLogin($request);
            }
        }
        if (!isset($p['model'])) {
            throw new Exception('The model class was not provided in the parameters.');
        }
        // Set the default
        $model = $p['model'];
        $context = (isset($p['extra_context'])) ? $p['extra_context'] : array();
        $template = (isset($p['template'])) ? $p['template'] : strtolower($model).'_create_form.html';
        $post_save_keys = (isset($p['post_save_redirect_keys'])) ? $p['post_save_redirect_keys'] : array('id');
 
 
        $object = new $model();
        if ($request->method == 'POST') {
            $form = Pluf_Shortcuts_GetFormForModel($object, $request->POST, $p['extra_form']);
            if ($form->isValid()) {
                $object = $form->save();
                if (isset($p['post_save_redirect'])) {
                    $url = Pluf_HTTP_URL_urlForView($p['post_save_redirect'],
                                                    $post_save_keys);
                } elseif (in_array('getAbsoluteUrl',
                                   get_class_methods($object))) {
                    $url = $object->getAbsoluteUrl();
                } else {
                    throw new Exception('No URL to redirect to from generic create view.');
                }
                if (!$request->user->isAnonymous()) {
                    $request->user->setMessage(sprintf(__('The %s was created successfully.'), $object->_a['verbose']));
                }
                return new Pluf_HTTP_Response_Redirect($url);
            }
        } else {
            $form = Pluf_Shortcuts_GetFormForModel($object, null, $p['extra_form']);
        }
        return Pluf_Shortcuts_RenderToResponse($template,
                                               array_merge($context,
                                                           array('form' => $form)),
                                               $request);
    }
 
    /**
     * Update an object (Part of the CRUD series).
     *
     * The minimal extra parameter is the model class name. The list
     * of extra parameters is:
     *
     * 'model' - Class name string, required.
     *
     * 'model_id' - Id of of the current model to update
     *
     * 'extra_context' - Array of key/values to be added to the
     *                   context (array())
     *
     * 'extra_form' - Array of key/values to be added to the
     *                   form generation (array())
     *
     * 'login_required' - Do we require login (false)
     *
     * 'template' - Template to use ('"model class"_update_form.html')
     *
     * 'post_save_redirect' - View to redirect after saving (use
     *                        getAbsoluteUrl() method of the mode)
     *
     * 'post_save_redirect_keys' - Which keys of the model to pass to
     *                             the view (array('id'))
     *
     * @param Pluf_HTTP_Request Request object
     * @param array Match
     * @param array Extra parameters
     * @return Pluf_HTTP_Response Response object (can be a redirect)
     */
    public function updateObject($request, $match, $p)
    {
        if (isset($p['login_required']) && true == $p['login_required']) {
            if ($request->user->isAnonymous()) {
                return new Pluf_HTTP_Response_RedirectToLogin($request);
            }
        }
        if (!isset($p['model'])) {
            throw new Exception('The model class was not provided in the parameters.');
        }
        // Set the default
        $model = $p['model'];
        $model_id = $p['model_id'];
        $context = (isset($p['extra_context'])) ? $p['extra_context'] : array();
        $template = (isset($p['template'])) ? $p['template'] : strtolower($model).'_update_form.html';
        $post_save_keys = (isset($p['post_save_redirect_keys'])) ? $p['post_save_redirect_keys'] : array('id');
 
        $object = Pluf_Shortcuts_GetObjectOr404($model, $model_id);
        if ($request->method == 'POST') {
            $form = Pluf_Shortcuts_GetFormForModel($object, $request->POST, $p['extra_form']);
            if ($form->isValid()) {
                $object = $form->save();
                if (isset($p['post_save_redirect'])) {
                    $url = Pluf_HTTP_URL_urlForView($p['post_save_redirect'],
                                                    $post_save_keys);
                } elseif (in_array('getAbsoluteUrl',
                                   get_class_methods($object))) {
                    $url = $object->getAbsoluteUrl();
                } else {
                    throw new Exception('No URL to redirect to from generic create view.');
                }
                if (!$request->user->isAnonymous()) {
                    $request->user->setMessage(sprintf(__('The %s was created successfully.'), $object->_a['verbose']));
                }
                return new Pluf_HTTP_Response_Redirect($url);
            }
        } else {
            $form = Pluf_Shortcuts_GetFormForModel($object, $object->getData(), $p['extra_form']);
        }
        return Pluf_Shortcuts_RenderToResponse($template,
                                               array_merge($context,
                                                           array('form' => $form,
                                                                 'object' => $object)),
                                               $request);
    }
 
 
    /**
     * Delete an object (Part of the CRUD series).
     *
     * The minimal extra parameter is the model class name. The list
     * of extra parameters is:
     *
     * 'model' - Class name string, required.
     *
     * 'post_delete_redirect' - View to redirect after saving, required.
     *
     * 'id' - Index in the match to fin the id of the object to delete (1)
     *
     * 'login_required' - Do we require login (false)
     *
     * 'template' - Template to use ('"model class"_confirm_delete.html')
     *
     * 'post_delete_redirect_keys' - Which keys of the model to pass to
     *                             the view (array())
     *
     * 'extra_context' - Array of key/values to be added to the
     *                   context (array())
     *
     * @param Pluf_HTTP_Request Request object
     * @param array Match
     * @param array Extra parameters
     * @return Pluf_HTTP_Response Response object (can be a redirect)
     */
    public function deleteObject($request, $match, $p)
    {
        if (isset($p['login_required']) && true == $p['login_required']) {
            if ($request->user->isAnonymous()) {
                return new Pluf_HTTP_Response_RedirectToLogin($request);
            }
        }
        if (!isset($p['model'])) {
            throw new Exception('The model class was not provided in the parameters.');
        }
        // Set the default
        $id = (isset($p['id'])) ? $match[$p['id']] : $match[1];
        $model = $p['model'];
        $context = (isset($p['extra_context'])) ? $p['extra_context'] : array();
        $template = (isset($p['template'])) ? $p['template'] : strtolower($model).'_confirm_delete.html';
        $post_save_keys = (isset($p['post_save_redirect_keys'])) ? $p['post_save_redirect_keys'] : array();
 
        $object = Pluf_Shortcuts_GetObjectOr404($model, $id);
        if ($request->method == 'POST') {
            $object->delete();
            if (isset($p['post_save_redirect'])) {
                $url = Pluf_HTTP_URL_urlForView($p['post_save_redirect'],
                                                $post_save_keys);
            } else {
                throw new Exception('No URL to redirect to from generic delete view.');
            }
            if (!$request->user->isAnonymous()) {
                $request->user->setMessage(sprintf(__('The %s was deleted successfully.'), $object->_a['verbose']));
            }
            return new Pluf_HTTP_Response_Redirect($url);
        }
        return Pluf_Shortcuts_RenderToResponse($template,
                                               array_merge($context,
                                                           array('object' => $object)),
                                               $request);
    }
 
}

Archive Download this file

Branches

Tags

Number of commits:
Page rendered in 0.08977s using 11 queries.