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