PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/protected/modules/user/controllers/ProfileFieldController.php

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