1 <?php
2
3 class ProfileFieldController extends Controller
4 {
5
6 7 8
9 private $_model;
10 private static $_widgets = array();
11 public $defaultAction = 'admin';
12 public $layout='//layouts/column2';
13
14 15 16
17 public function filters()
18 {
19 return CMap::mergeArray(parent::filters(),array(
20 'accessControl',
21 ));
22 }
23
24 25 26 27 28
29 public function accessRules()
30 {
31 return array(
32 array('allow',
33 'actions'=>array('*'),
34 'users'=>array('*'),
35 ),
36 array('allow',
37 'actions'=>array('create','update','view','admin','delete'),
38 'users'=>UserModule::getAdmins(),
39 ),
40 array('deny',
41 'users'=>array('*'),
42 ),
43 );
44 }
45
46 47 48
49 public function actionView()
50 {
51 $this->render('view',array(
52 'model'=>$this->loadModel(),
53 ));
54 }
55
56 57 58
59 public function registerScript() {
60 $basePath=Yii::getPathOfAlias('application.modules.user.views.asset');
61 $baseUrl=Yii::app()->getAssetManager()->publish($basePath);
62 $cs = Yii::app()->getClientScript();
63 $cs->registerCoreScript('jquery');
64 $cs->registerCssFile($baseUrl.'/css/redmond/jquery-ui.css');
65 $cs->registerCssFile($baseUrl.'/css/style.css');
66 $cs->registerScriptFile($baseUrl.'/js/jquery-ui.min.js');
67 $cs->registerScriptFile($baseUrl.'/js/form.js');
68 $cs->registerScriptFile($baseUrl.'/js/jquery.json.js');
69
70 $widgets = self::getWidgets();
71
72 $wgByTypes = ProfileField::itemAlias('field_type');
73 foreach ($wgByTypes as $k=>$v) {
74 $wgByTypes[$k] = array();
75 }
76
77 foreach ($widgets[1] as $widget) {
78 if (isset($widget['fieldType'])&&count($widget['fieldType'])) {
79 foreach($widget['fieldType'] as $type) {
80 array_push($wgByTypes[$type],$widget['name']);
81 }
82 }
83 }
84
85 $js = "
86
87 var name = $('#name'),
88 value = $('#value'),
89 allFields = $([]).add(name).add(value),
90 tips = $('.validateTips');
91
92 var listWidgets = jQuery.parseJSON('".str_replace("'","\'",CJavaScript::jsonEncode($widgets[0]))."');
93 var widgets = jQuery.parseJSON('".str_replace("'","\'",CJavaScript::jsonEncode($widgets[1]))."');
94 var wgByType = jQuery.parseJSON('".str_replace("'","\'",CJavaScript::jsonEncode($wgByTypes))."');
95
96 var fieldType = {
97 'INTEGER':{
98 'hide':['match','other_validator','widgetparams'],
99 'val':{
100 'field_size':10,
101 'default':'0',
102 'range':'',
103 'widgetparams':''
104 }
105 },
106 'VARCHAR':{
107 'hide':['widgetparams'],
108 'val':{
109 'field_size':255,
110 'default':'',
111 'range':'',
112 'widgetparams':''
113 }
114 },
115 'TEXT':{
116 'hide':['field_size','range','widgetparams'],
117 'val':{
118 'field_size':0,
119 'default':'',
120 'range':'',
121 'widgetparams':''
122 }
123 },
124 'DATE':{
125 'hide':['field_size','field_size_min','match','range','widgetparams'],
126 'val':{
127 'field_size':0,
128 'default':'0000-00-00',
129 'range':'',
130 'widgetparams':''
131 }
132 },
133 'FLOAT':{
134 'hide':['match','other_validator','widgetparams'],
135 'val':{
136 'field_size':'10.2',
137 'default':'0.00',
138 'range':'',
139 'widgetparams':''
140 }
141 },
142 'DECIMAL':{
143 'hide':['match','other_validator','widgetparams'],
144 'val':{
145 'field_size':'10,2',
146 'default':'0',
147 'range':'',
148 'widgetparams':''
149 }
150 },
151 'BOOL':{
152 'hide':['field_size','field_size_min','match','widgetparams'],
153 'val':{
154 'field_size':0,
155 'default':0,
156 'range':'1==".UserModule::t('Yes').";0==".UserModule::t('No')."',
157 'widgetparams':''
158 }
159 },
160 'BLOB':{
161 'hide':['field_size','field_size_min','match','widgetparams'],
162 'val':{
163 'field_size':0,
164 'default':'',
165 'range':'',
166 'widgetparams':''
167 }
168 },
169 'BINARY':{
170 'hide':['field_size','field_size_min','match','widgetparams'],
171 'val':{
172 'field_size':0,
173 'default':'',
174 'range':'',
175 'widgetparams':''
176 }
177 }
178 };
179
180 function showWidgetList(type) {
181 $('div.widget select').empty();
182 $('div.widget select').append('<option value=\"\">".UserModule::t('No')."</option>');
183 if (wgByType[type]) {
184 for (var k in wgByType[type]) {
185 $('div.widget select').append('<option value=\"'+wgByType[type][k]+'\">'+widgets[wgByType[type][k]]['label']+'</option>');
186 }
187 }
188 }
189
190 function setFields(type) {
191 if (fieldType[type]) {
192 if (".((isset($_GET['id']))?0:1).") {
193 showWidgetList(type);
194 $('#widgetlist option:first').attr('selected', 'selected');
195 }
196
197 $('div.row').addClass('toshow').removeClass('tohide');
198 if (fieldType[type].hide.length) $('div.'+fieldType[type].hide.join(', div.')).addClass('tohide').removeClass('toshow');
199 if ($('div.widget select').val()) {
200 $('div.widgetparams').removeClass('tohide');
201 }
202 $('div.toshow').show(500);
203 $('div.tohide').hide(500);
204 ".((!isset($_GET['id']))?"
205 for (var k in fieldType[type].val) {
206 $('div.'+k+' input').val(fieldType[type].val[k]);
207 }":'')."
208 }
209 }
210
211 function isArray(obj) {
212 if (obj.constructor.toString().indexOf('Array') == -1)
213 return false;
214 else
215 return true;
216 }
217
218 $('#dialog-form').dialog({
219 autoOpen: false,
220 height: 400,
221 width: 400,
222 modal: true,
223 buttons: {
224 '".UserModule::t('Save')."': function() {
225 var wparam = {};
226 var fparam = {};
227 $('#dialog-form fieldset .wparam').each(function(){
228 if ($(this).val()) wparam[$(this).attr('name')] = $(this).val();
229 });
230
231 var tab = $('#tabs ul li.ui-tabs-selected').text();
232 fparam[tab] = {};
233 $('#dialog-form fieldset .tab-'+tab).each(function(){
234 if ($(this).val()) fparam[tab][$(this).attr('name')] = $(this).val();
235 });
236
237 if ($.JSON.encode(wparam)!='{}') $('div.widgetparams input').val($.JSON.encode(wparam));
238 if ($.JSON.encode(fparam[tab])!='{}') $('div.other_validator input').val($.JSON.encode(fparam));
239
240 $(this).dialog('close');
241 },
242 '".UserModule::t('Cancel')."': function() {
243 $(this).dialog('close');
244 }
245 },
246 close: function() {
247 }
248 });
249
250
251 $('#widgetparams').focus(function() {
252 var widget = widgets[$('#widgetlist').val()];
253 var html = '';
254 var wparam = ($('div.widgetparams input').val())?$.JSON.decode($('div.widgetparams input').val()):{};
255 var fparam = ($('div.other_validator input').val())?$.JSON.decode($('div.other_validator input').val()):{};
256
257 // Class params
258 for (var k in widget.params) {
259 html += '<label for=\"name\">'+((widget.paramsLabels[k])?widget.paramsLabels[k]:k)+'</label>';
260 html += '<input type=\"text\" name=\"'+k+'\" id=\"widget_'+k+'\" class=\"text wparam ui-widget-content ui-corner-all\" value=\"'+((wparam[k])?wparam[k]:widget.params[k])+'\" />';
261 }
262 // Validator params
263 if (widget.other_validator) {
264 var tabs = '';
265 var li = '';
266 for (var t in widget.other_validator) {
267 tabs += '<div id=\"tab-'+t+'\" class=\"tab\">';
268 li += '<li'+((fparam[t])?' class=\"ui-tabs-selected\"':'')+'><a href=\"#tab-'+t+'\">'+t+'</a></li>';
269
270 for (var k in widget.other_validator[t]) {
271 tabs += '<label for=\"name\">'+((widget.paramsLabels[k])?widget.paramsLabels[k]:k)+'</label>';
272 if (isArray(widget.other_validator[t][k])) {
273 tabs += '<select type=\"text\" name=\"'+k+'\" id=\"filter_'+k+'\" class=\"text fparam ui-widget-content ui-corner-all tab-'+t+'\">';
274 for (var i in widget.other_validator[t][k]) {
275 tabs += '<option value=\"'+widget.other_validator[t][k][i]+'\"'+((fparam[t]&&fparam[t][k])?' selected=\"selected\"':'')+'>'+widget.other_validator[t][k][i]+'</option>';
276 }
277 tabs += '</select>';
278 } else {
279 tabs += '<input type=\"text\" name=\"'+k+'\" id=\"filter_'+k+'\" class=\"text fparam ui-widget-content ui-corner-all tab-'+t+'\" value=\"'+((fparam[t]&&fparam[t][k])?fparam[t][k]:widget.other_validator[t][k])+'\" />';
280 }
281 }
282 tabs += '</div>';
283 }
284 html += '<div id=\"tabs\"><ul>'+li+'</ul>'+tabs+'</div>';
285 }
286
287 $('#dialog-form fieldset').html(html);
288
289 $('#tabs').tabs();
290
291 // Show form
292 $('#dialog-form').dialog('open');
293 });
294
295 $('#field_type').change(function() {
296 setFields($(this).val());
297 });
298
299 $('#widgetlist').change(function() {
300 if ($(this).val()) {
301 $('div.widgetparams').show(500);
302 } else {
303 $('div.widgetparams').hide(500);
304 }
305
306 });
307
308 // show all function
309 $('div.form p.note').append('<br/><a href=\"#\" id=\"showAll\">".UserModule::t('Show all')."</a>');
310 $('#showAll').click(function(){
311 $('div.row').show(500);
312 return false;
313 });
314
315 // init
316 setFields($('#field_type').val());
317
318 ";
319 $cs->registerScript(__CLASS__.'#dialog', $js);
320 }
321
322 323 324 325
326 public function actionCreate()
327 {
328 $model=new ProfileField;
329 $scheme = get_class(Yii::app()->db->schema);
330 if(isset($_POST['ProfileField']))
331 {
332 $model->attributes=$_POST['ProfileField'];
333
334 if($model->validate()) {
335 $sql = 'ALTER TABLE '.Profile::model()->tableName().' ADD `'.$model->varname.'` ';
336 $sql .= $this->fieldType($model->field_type);
337 if (
338 $model->field_type!='TEXT'
339 && $model->field_type!='DATE'
340 && $model->field_type!='BOOL'
341 && $model->field_type!='BLOB'
342 && $model->field_type!='BINARY'
343 )
344 $sql .= '('.$model->field_size.')';
345 $sql .= ' NOT NULL ';
346
347 if ($model->field_type!='TEXT'&&$model->field_type!='BLOB'||$scheme!='CMysqlSchema') {
348 if ($model->default)
349 $sql .= " DEFAULT '".$model->default."'";
350 else
351 $sql .= ((
352 $model->field_type=='TEXT'
353 ||$model->field_type=='VARCHAR'
354 ||$model->field_type=='BLOB'
355 ||$model->field_type=='BINARY'
356 )?" DEFAULT ''":(($model->field_type=='DATE')?" DEFAULT '0000-00-00'":" DEFAULT 0"));
357 }
358 $model->dbConnection->createCommand($sql)->execute();
359 $model->save();
360 $this->redirect(array('view','id'=>$model->id));
361 }
362 }
363
364 $this->registerScript();
365 $this->render('create',array(
366 'model'=>$model,
367 ));
368 }
369
370 371 372 373
374 public function actionUpdate()
375 {
376 $model=$this->loadModel();
377 if(isset($_POST['ProfileField']))
378 {
379 $model->attributes=$_POST['ProfileField'];
380 if($model->save())
381 $this->redirect(array('view','id'=>$model->id));
382 }
383 $this->registerScript();
384
385 $this->render('update',array(
386 'model'=>$model,
387 ));
388 }
389
390 391 392 393
394 public function actionDelete()
395 {
396 if(Yii::app()->request->isPostRequest)
397 {
398
399 $scheme = get_class(Yii::app()->db->schema);
400 $model = $this->loadModel();
401 if ($scheme=='CSqliteSchema') {
402 $attr = Profile::model()->attributes;
403 unset($attr[$model->varname]);
404 $attr = array_keys($attr);
405 $connection=Yii::app()->db;
406 $transaction=$connection->beginTransaction();
407 $status=true;
408 try
409 {
410 $sql = '';
411 $connection->createCommand(
412 "CREATE TEMPORARY TABLE ".Profile::model()->tableName()."_backup (".implode(',',$attr).")"
413 )->execute();
414
415 $connection->createCommand(
416 "INSERT INTO ".Profile::model()->tableName()."_backup SELECT ".implode(',',$attr)." FROM ".Profile::model()->tableName()
417 )->execute();
418
419 $connection->createCommand(
420 "DROP TABLE ".Profile::model()->tableName()
421 )->execute();
422
423 $connection->createCommand(
424 "CREATE TABLE ".Profile::model()->tableName()." (".implode(',',$attr).")"
425 )->execute();
426
427 $connection->createCommand(
428 "INSERT INTO ".Profile::model()->tableName()." SELECT ".implode(',',$attr)." FROM ".Profile::model()->tableName()."_backup"
429 )->execute();
430
431 $connection->createCommand(
432 "DROP TABLE ".Profile::model()->tableName()."_backup"
433 )->execute();
434
435 $transaction->commit();
436 }
437 catch(Exception $e)
438 {
439 $transaction->rollBack();
440 $status=false;
441 }
442 if ($status) {
443 $model->delete();
444 }
445
446 } else {
447 $sql = 'ALTER TABLE '.Profile::model()->tableName().' DROP `'.$model->varname.'`';
448 if ($model->dbConnection->createCommand($sql)->execute()) {
449 $model->delete();
450 }
451 }
452
453
454 if(!isset($_POST['ajax']))
455 $this->redirect(array('admin'));
456 }
457 else
458 throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
459 }
460
461 462 463
464 public function actionAdmin()
465 {
466 $model=new ProfileField('search');
467 $model->unsetAttributes();
468 if(isset($_GET['ProfileField']))
469 $model->attributes=$_GET['ProfileField'];
470
471 $this->render('admin',array(
472 'model'=>$model,
473 ));
474 475 476 477 478 479 480 481 482 483 484 485 486
487 }
488
489 490 491 492
493 public function loadModel()
494 {
495 if($this->_model===null)
496 {
497 if(isset($_GET['id']))
498 $this->_model=ProfileField::model()->findbyPk($_GET['id']);
499 if($this->_model===null)
500 throw new CHttpException(404,'The requested page does not exist.');
501 }
502 return $this->_model;
503 }
504
505 506 507 508 509
510 public function fieldType($type) {
511 $type = str_replace('UNIX-DATE','INTEGER',$type);
512 return $type;
513 }
514
515 public static function getWidgets($fieldType='') {
516 $basePath=Yii::getPathOfAlias('application.modules.user.components');
517 $widgets = array();
518 $list = array(''=>UserModule::t('No'));
519 if (self::$_widgets) {
520 $widgets = self::$_widgets;
521 } else {
522 $d = dir($basePath);
523 while (false !== ($file = $d->read())) {
524 if (strpos($file,'UW')===0) {
525 list($className) = explode('.',$file);
526 if (class_exists($className)) {
527 $widgetClass = new $className;
528 if ($widgetClass->init()) {
529 $widgets[$className] = $widgetClass->init();
530 if ($fieldType) {
531 if (in_array($fieldType,$widgets[$className]['fieldType'])) $list[$className] = $widgets[$className]['label'];
532 } else {
533 $list[$className] = $widgets[$className]['label'];
534 }
535 }
536 }
537 }
538 }
539 $d->close();
540 }
541 return array($list,$widgets);
542 }
543
544 545 546 547
548 public function actionGetDroDownDepValues(){
549 $post = $_POST;
550 $model = new $post['model'];
551 $data = CHtml::listData($model->findAll($post['varname'].'=:'.$post['varname'], array(':'.$post['varname']=>$post[$post['varname']])), 'id', $post['optionDestName']);
552 echo CHtml::tag('option', array('value'=>''), CHtml::encode('Seleccione...'), true);
553 foreach($data AS $value=>$name){
554 echo CHtml::tag('option', array('value'=>$value), CHtml::encode($name), true);
555 }
556 }
557
558 559 560 561
562 protected function performAjaxValidation($model)
563 {
564 if(isset($_POST['ajax']) && $_POST['ajax']==='profile-field-form')
565 {
566 echo CActiveForm::validate($model);
567 Yii::app()->end();
568 }
569 }
570 }
571