Gentics Portal.Node PHP API
 All Classes Namespaces Functions Variables Pages
ProfileFieldController.php
1 <?php
2 
4 {
5 
6  /**
7  * @var CActiveRecord the currently loaded data model instance.
8  */
9  private $_model;
10  private static $_widgets = array();
11  public $defaultAction = 'admin';
12 
13  /**
14  * @return array action filters
15  */
16  public function filters()
17  {
18  return CMap::mergeArray(parent::filters(), array(
19  'accessControl', // perform access control for CRUD operations
20  ));
21  }
22 
23  /**
24  * Specifies the access control rules.
25  * This method is used by the 'accessControl' filter.
26  * @return array access control rules
27  */
28  public function accessRules()
29  {
30  return array(
31 // array('allow', // allow all users to perform 'index' and 'view' actions
32 // 'actions' => array('*'),
33 // 'users' => array('*'),
34 // ),
35  array('allow', // allow admin user to perform 'admin' and 'delete' actions
36  'actions' => array('create', 'update', 'view', 'admin', 'delete'),
37  'roles' => array('Admin'),
38  ),
39  array('deny', // deny all users
40  'users' => array('*'),
41  ),
42  );
43  }
44 
45  /**
46  * Displays a particular model.
47  */
48  public function actionView()
49  {
50  $this->render('view', array(
51  'model' => $this->loadModel(),
52  ));
53  }
54  /**
55  * Clear cache to load new db schema
56  */
57  public function afterAction($action)
58  {
59  Yii::app()->cache->flush();
60  parent::afterAction($action);
61  }
62 
63  /**
64  * Register Script
65  */
66  public function registerScript()
67  {
68  // $basePath=Yii::getPathOfAlias('application.modules.user.views.asset');
69  $basePath = Yii::app()->getModule('user')->getBasePath() . '/views/asset';
70  $baseUrl = Yii::app()->getModule('user')->getAssetsUrl();
71  $cs = Yii::app()->getClientScript();
72  $coreBaseUrl = $cs->getCoreScriptUrl();
73  $cs->registerCoreScript('jquery');
74  $cs->registerCssFile($coreBaseUrl . '/jui/css/base/jquery-ui.css', '', null, false);
75  $cs->registerCssFile($baseUrl . '/css/style.css');
76  $cs->registerScriptFile($coreBaseUrl . '/jui/js/jquery-ui.min.js');
77  $cs->registerScriptFile($baseUrl . '/js/form.js');
78  $cs->registerScriptFile($baseUrl . '/js/jquery.json.js');
79 
80  $widgets = self::getWidgets();
81 
82  $wgByTypes = ProfileField::itemAlias('field_type');
83  foreach ($wgByTypes as $k => $v) {
84  $wgByTypes[$k] = array();
85  }
86 
87  foreach ($widgets[1] as $widget) {
88  if (isset($widget['fieldType']) && count($widget['fieldType'])) {
89  foreach ($widget['fieldType'] as $type) {
90  array_push($wgByTypes[$type], $widget['name']);
91  }
92  }
93  }
94  //echo '<pre>'; print_r($widgets[1]); die();
95  $js = "
96 
97  var name = $('#name'),
98  value = $('#value'),
99  allFields = $([]).add(name).add(value),
100  tips = $('.validateTips');
101 
102  var listWidgets = jQuery.parseJSON('" . str_replace("'", "\'", CJavaScript::jsonEncode($widgets[0])) . "');
103  var widgets = jQuery.parseJSON('" . str_replace("'", "\'", CJavaScript::jsonEncode($widgets[1])) . "');
104  var wgByType = jQuery.parseJSON('" . str_replace("'", "\'", CJavaScript::jsonEncode($wgByTypes)) . "');
105 
106  var fieldType = {
107  'INTEGER':{
108  'hide':['match','other_validator','widgetparams'],
109  'val':{
110  'field_size':10,
111  'default':'0',
112  'range':'',
113  'widgetparams':''
114  }
115  },
116  'VARCHAR':{
117  'hide':['widgetparams'],
118  'val':{
119  'field_size':255,
120  'default':'',
121  'range':'',
122  'widgetparams':''
123  }
124  },
125  'TEXT':{
126  'hide':['field_size','range','widgetparams'],
127  'val':{
128  'field_size':0,
129  'default':'',
130  'range':'',
131  'widgetparams':''
132  }
133  },
134  'DATE':{
135  'hide':['field_size','field_size_min','match','range','widgetparams'],
136  'val':{
137  'field_size':0,
138  'default':'0000-00-00',
139  'range':'',
140  'widgetparams':''
141  }
142  },
143  'FLOAT':{
144  'hide':['match','other_validator','widgetparams'],
145  'val':{
146  'field_size':'10,2',
147  'default':'0.00',
148  'range':'',
149  'widgetparams':''
150  }
151  },
152  'BOOL':{
153  'hide':['field_size','field_size_min','match','widgetparams'],
154  'val':{
155  'field_size':0,
156  'default':0,
157  'range':'1==" . UserModule::t('Yes') . ";0==" . UserModule::t('No') . "',
158  'widgetparams':''
159  }
160  },
161  'BLOB':{
162  'hide':['field_size','field_size_min','match','widgetparams'],
163  'val':{
164  'field_size':0,
165  'default':'',
166  'range':'',
167  'widgetparams':''
168  }
169  },
170  'BINARY':{
171  'hide':['field_size','field_size_min','match','widgetparams'],
172  'val':{
173  'field_size':0,
174  'default':'',
175  'range':'',
176  'widgetparams':''
177  }
178  }
179  };
180 
181  function showWidgetList(type) {
182  $('div.widget select').empty();
183  $('div.widget select').append('<option value=\"\">" . UserModule::t('No') . "</option>');
184  if (wgByType[type]) {
185  for (var k in wgByType[type]) {
186  $('div.widget select').append('<option value=\"'+wgByType[type][k]+'\">'+widgets[wgByType[type][k]]['label']+'</option>');
187  }
188  }
189  }
190 
191  function setFields(type) {
192  if (fieldType[type]) {
193  if (" . ((isset($_GET['id'])) ? 0 : 1) . ") {
194  showWidgetList(type);
195  $('#widgetlist option:first').attr('selected', 'selected');
196  }
197 
198  $('div.row').addClass('toshow').removeClass('tohide');
199  if (fieldType[type].hide.length) $('div.'+fieldType[type].hide.join(', div.')).addClass('tohide').removeClass('toshow');
200  if ($('div.widget select').val()) {
201  $('div.widgetparams').removeClass('tohide');
202  }
203  $('div.toshow').show(500);
204  $('div.tohide').hide(500);
205  " . ((!isset($_GET['id'])) ? "
206  for (var k in fieldType[type].val) {
207  $('div.'+k+' input').val(fieldType[type].val[k]);
208  }" : '') . "
209  }
210  }
211 
212  function isArray(obj) {
213  if (obj.constructor.toString().indexOf('Array') == -1)
214  return false;
215  else
216  return true;
217  }
218 
219  $('#dialog-form').dialog({
220  autoOpen: false,
221  height: 400,
222  width: 400,
223  modal: true,
224  buttons: {
225  '" . UserModule::t('Save') . "': function() {
226  var wparam = {};
227  var fparam = {};
228  $('#dialog-form fieldset .wparam').each(function(){
229  if ($(this).val()) wparam[$(this).attr('name')] = $(this).val();
230  });
231 
232  var tab = $('#tabs ul li.ui-tabs-selected').text();
233  fparam[tab] = {};
234  $('#dialog-form fieldset .tab-'+tab).each(function(){
235  if ($(this).val()) fparam[tab][$(this).attr('name')] = $(this).val();
236  });
237 
238  if ($.JSON.encode(wparam)!='{}') $('div.widgetparams input').val($.JSON.encode(wparam));
239  if ($.JSON.encode(fparam[tab])!='{}') $('div.other_validator input').val($.JSON.encode(fparam));
240 
241  $(this).dialog('close');
242  },
243  '" . UserModule::t('Cancel') . "': function() {
244  $(this).dialog('close');
245  }
246  },
247  close: function() {
248  }
249  });
250 
251 
252  $('#widgetparams').focus(function() {
253  var widget = widgets[$('#widgetlist').val()];
254  var html = '';
255  var wparam = ($('div.widgetparams input').val())?$.JSON.decode($('div.widgetparams input').val()):{};
256  var fparam = ($('div.other_validator input').val())?$.JSON.decode($('div.other_validator input').val()):{};
257 
258  // Class params
259  for (var k in widget.params) {
260  html += '<label for=\"name\">'+((widget.paramsLabels[k])?widget.paramsLabels[k]:k)+'</label>';
261  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])+'\" />';
262  }
263  // Validator params
264  if (widget.other_validator) {
265  var tabs = '';
266  var li = '';
267  for (var t in widget.other_validator) {
268  tabs += '<div id=\"tab-'+t+'\" class=\"tab\">';
269  li += '<li'+((fparam[t])?' class=\"ui-tabs-selected\"':'')+'><a href=\"#tab-'+t+'\">'+t+'</a></li>';
270 
271  for (var k in widget.other_validator[t]) {
272  tabs += '<label for=\"name\">'+((widget.paramsLabels[k])?widget.paramsLabels[k]:k)+'</label>';
273  if (isArray(widget.other_validator[t][k])) {
274  tabs += '<select type=\"text\" name=\"'+k+'\" id=\"filter_'+k+'\" class=\"text fparam ui-widget-content ui-corner-all tab-'+t+'\">';
275  for (var i in widget.other_validator[t][k]) {
276  tabs += '<option value=\"'+widget.other_validator[t][k][i]+'\"'+((fparam[t]&&fparam[t][k])?' selected=\"selected\"':'')+'>'+widget.other_validator[t][k][i]+'</option>';
277  }
278  tabs += '</select>';
279  } else {
280  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])+'\" />';
281  }
282  }
283  tabs += '</div>';
284  }
285  html += '<div id=\"tabs\"><ul>'+li+'</ul>'+tabs+'</div>';
286  }
287 
288  $('#dialog-form fieldset').html(html);
289 
290  $('#tabs').tabs();
291 
292  // Show form
293  $('#dialog-form').dialog('open');
294  });
295 
296  $('#field_type').change(function() {
297  setFields($(this).val());
298  });
299 
300  $('#widgetlist').change(function() {
301  if ($(this).val()) {
302  $('div.widgetparams').show(500);
303  } else {
304  $('div.widgetparams').hide(500);
305  }
306 
307  });
308 
309  // show all function
310  $('div.form p.note').append('<br/><a href=\"#\" id=\"showAll\">" . UserModule::t('Show all') . "</a>');
311  $('#showAll').click(function(){
312  $('div.row').show(500);
313  return false;
314  });
315 
316  // init
317  setFields($('#field_type').val());
318 
319  ";
320  $cs->registerScript(__CLASS__ . '#dialog', $js);
321  }
322 
323  /**
324  * Creates a new model.
325  * If creation is successful, the browser will be redirected to the 'view' page.
326  */
327  public function actionCreate()
328  {
329  $model = new ProfileField;
330  $scheme = get_class(Yii::app()->db->schema);
331  if (isset($_POST['ProfileField'])) {
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  * Updates a particular model.
372  * If update is successful, the browser will be redirected to the 'view' page.
373  */
374  public function actionUpdate()
375  {
376  $model = $this->loadModel();
377  if (isset($_POST['ProfileField'])) {
378  $model->attributes = $_POST['ProfileField'];
379  if ($model->save())
380  $this->redirect(array('view', 'id' => $model->id));
381  }
382  $this->registerScript();
383 
384  $this->render('update', array(
385  'model' => $model,
386  ));
387  }
388 
389  /**
390  * Deletes a particular model.
391  * If deletion is successful, the browser will be redirected to the 'index' page.
392  */
393  public function actionDelete()
394  {
395  /* row below was commented out to allow delete fields from GET requests too*/
396  //if (Yii::app()->request->isPostRequest) {
397  // we only allow deletion via POST request
398  $scheme = get_class(Yii::app()->db->schema);
399  $model = $this->loadModel();
400  if ($scheme == 'CSqliteSchema') {
401  $attr = Profile::model()->attributes;
402  unset($attr[$model->varname]);
403  $attr = array_keys($attr);
404  $connection = Yii::app()->db;
405  $transaction = $connection->beginTransaction();
406  $status = true;
407  try {
408  $sql = '';
409  $connection->createCommand(
410  "CREATE TEMPORARY TABLE " . Profile::model()->tableName() . "_backup (" . implode(',', $attr) . ")"
411  )->execute();
412 
413  $connection->createCommand(
414  "INSERT INTO " . Profile::model()->tableName() . "_backup SELECT " . implode(',', $attr) . " FROM " . Profile::model()->tableName()
415  )->execute();
416 
417  $connection->createCommand(
418  "DROP TABLE " . Profile::model()->tableName()
419  )->execute();
420 
421  $connection->createCommand(
422  "CREATE TABLE " . Profile::model()->tableName() . " (" . implode(',', $attr) . ")"
423  )->execute();
424 
425  $connection->createCommand(
426  "INSERT INTO " . Profile::model()->tableName() . " SELECT " . implode(',', $attr) . " FROM " . Profile::model()->tableName() . "_backup"
427  )->execute();
428 
429  $connection->createCommand(
430  "DROP TABLE " . Profile::model()->tableName() . "_backup"
431  )->execute();
432 
433  $transaction->commit();
434  } catch (Exception $e) {
435  $transaction->rollBack();
436  $status = false;
437  }
438  if ($status) {
439  $model->delete();
440  }
441 
442  } else {
443  $sql = 'ALTER TABLE ' . Profile::model()->tableName() . ' DROP `' . $model->varname . '`';
444  if ($model->dbConnection->createCommand($sql)->execute()) {
445  $model->delete();
446  }
447  }
448 
449  // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
450  if (!isset($_POST['ajax'])) {
451  $this->redirect(array('admin'));
452  }
453  /* rows below were commented out to allow delete fields from GET requests too*/
454  //} else
455  // throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
456  }
457 
458  /**
459  * Manages all models.
460  */
461  public function actionAdmin()
462  {
463  $model = new ProfileField('search');
464  $model->field_size = null;
465  $model->required = null;
466  $model->position = null;
467  $model->visible = null;
468  if (isset($_GET['ProfileField'])) {
469  $model->attributes = $_GET['ProfileField'];
470  }
471 
472  $this->render('admin', array(
473  'model' => $model,
474  ));
475  }
476 
477  /**
478  * Returns the data model based on the primary key given in the GET variable.
479  * If the data model is not found, an HTTP exception will be raised.
480  */
481  public function loadModel()
482  {
483  if ($this->_model === null) {
484  if (isset($_GET['id']))
485  $this->_model = ProfileField::model()->findbyPk($_GET['id']);
486  if ($this->_model === null)
487  throw new CHttpException(404, 'The requested page does not exist.');
488  }
489  return $this->_model;
490  }
491 
492  /**
493  * MySQL field type
494  * @param $type string
495  * @return string
496  */
497  public function fieldType($type)
498  {
499  $type = str_replace('UNIX-DATE', 'INTEGER', $type);
500  return $type;
501  }
502 
503  public static function getWidgets($fieldType = '')
504  {
505  // $basePath=Yii::getPathOfAlias('application.modules.user.components');
506  $basePath = Yii::app()->getModule('user')->getBasePath() . '/components';
507  $widgets = array();
508  $list = array('' => UserModule::t('No'));
509  if (self::$_widgets) {
510  $widgets = self::$_widgets;
511  } else {
512  $d = dir($basePath);
513  while (false !== ($file = $d->read())) {
514  if (strpos($file, 'UW') === 0) {
515  list($className) = explode('.', $file);
516  if (class_exists($className)) {
517  $widgetClass = new $className;
518  if ($widgetClass->init()) {
519  $widgets[$className] = $widgetClass->init();
520  if ($fieldType) {
521  if (in_array($fieldType, $widgets[$className]['fieldType'])) $list[$className] = $widgets[$className]['label'];
522  } else {
523  $list[$className] = $widgets[$className]['label'];
524  }
525  }
526  }
527  }
528  }
529  $d->close();
530  }
531  return array($list, $widgets);
532  }
533 }