PageRenderTime 73ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/application/libraries/grocery_crud.php

https://bitbucket.org/masangga/laperbanget
PHP | 4906 lines | 3642 code | 719 blank | 545 comment | 494 complexity | cf270da4489c18f3567ffe13db15cfbe MD5 | raw file
  1. <?php
  2. /**
  3. * PHP grocery CRUD
  4. *
  5. * A Codeigniter library that creates a CRUD automatically with just few lines of code.
  6. *
  7. * Copyright (C) 2010 - 2012 John Skoumbourdis.
  8. *
  9. * LICENSE
  10. *
  11. * Grocery CRUD is released with dual licensing, using the GPL v3 (license-gpl3.txt) and the MIT license (license-mit.txt).
  12. * You don't have to do anything special to choose one license or the other and you don't have to notify anyone which license you are using.
  13. * Please see the corresponding license file for details of these licenses.
  14. * You are free to use, modify and distribute this software, but all copyright information must remain.
  15. *
  16. * @package grocery CRUD
  17. * @copyright Copyright (c) 2010 through 2012, John Skoumbourdis
  18. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  19. * @version 1.3
  20. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  21. */
  22. // ------------------------------------------------------------------------
  23. /**
  24. * grocery Field Types
  25. *
  26. * The types of the fields and the default reactions
  27. *
  28. * @package grocery CRUD
  29. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  30. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  31. * @link http://www.grocerycrud.com/documentation
  32. */
  33. class grocery_CRUD_Field_Types
  34. {
  35. /**
  36. * Gets the field types of the main table.
  37. * @return array
  38. */
  39. public function get_field_types()
  40. {
  41. if($this->field_types !== null)
  42. return $this->field_types;
  43. $types = array();
  44. foreach($this->basic_model->get_field_types_basic_table() as $field_info)
  45. {
  46. $field_info->required = !empty($this->required_fields) && in_array($field_info->name,$this->required_fields) ? true : false;
  47. $field_info->display_as =
  48. isset($this->display_as[$field_info->name]) ?
  49. $this->display_as[$field_info->name] :
  50. ucfirst(str_replace("_"," ",$field_info->name));
  51. if($this->change_field_type !== null && isset($this->change_field_type[$field_info->name]))
  52. {
  53. $field_type = $this->change_field_type[$field_info->name];
  54. $field_info->crud_type = $field_type->type;
  55. $field_info->extras = $field_type->extras;
  56. $real_type = $field_info->crud_type;
  57. }
  58. elseif(isset($this->relation[$field_info->name]))
  59. {
  60. $real_type = 'relation';
  61. $field_info->crud_type = 'relation';
  62. }
  63. elseif(isset($this->upload_fields[$field_info->name]))
  64. {
  65. $real_type = 'upload_file';
  66. $field_info->crud_type = 'upload_file';
  67. }
  68. else
  69. {
  70. $real_type = $this->get_type($field_info);
  71. $field_info->crud_type = $real_type;
  72. }
  73. switch ($real_type) {
  74. case 'text':
  75. if(!empty($this->unset_texteditor) && in_array($field_info->name,$this->unset_texteditor))
  76. $field_info->extras = false;
  77. else
  78. $field_info->extras = 'text_editor';
  79. break;
  80. case 'relation':
  81. $field_info->extras = $this->relation[$field_info->name];
  82. break;
  83. case 'upload_file':
  84. $field_info->extras = $this->upload_fields[$field_info->name];
  85. break;
  86. default:
  87. if(empty($field_info->extras))
  88. $field_info->extras = false;
  89. break;
  90. }
  91. $types[$field_info->name] = $field_info;
  92. }
  93. if(!empty($this->relation_n_n))
  94. {
  95. foreach($this->relation_n_n as $field_name => $field_extras)
  96. {
  97. $field_info = (object)array();
  98. $field_info->name = $field_name;
  99. $field_info->crud_type = 'relation_n_n';
  100. $field_info->extras = $field_extras;
  101. $field_info->required = !empty($this->required_fields) && in_array($field_name,$this->required_fields) ? true : false;;
  102. $field_info->display_as =
  103. isset($this->display_as[$field_name]) ?
  104. $this->display_as[$field_name] :
  105. ucfirst(str_replace("_"," ",$field_name));
  106. $types[$field_name] = $field_info;
  107. }
  108. }
  109. if(!empty($this->add_fields))
  110. foreach($this->add_fields as $field_object)
  111. {
  112. $field_name = isset($field_object->field_name) ? $field_object->field_name : $field_object;
  113. if(!isset($types[$field_name]))
  114. {
  115. $field_info = (object)array(
  116. 'name' => $field_name,
  117. 'crud_type' => $this->change_field_type !== null && isset($this->change_field_type[$field_name]) ?
  118. $this->change_field_type[$field_name]->type :
  119. 'string',
  120. 'display_as' => isset($this->display_as[$field_name]) ?
  121. $this->display_as[$field_name] :
  122. ucfirst(str_replace("_"," ",$field_name)),
  123. 'required' => in_array($field_name,$this->required_fields) ? true : false
  124. );
  125. $types[$field_name] = $field_info;
  126. }
  127. }
  128. if(!empty($this->edit_fields))
  129. foreach($this->edit_fields as $field_object)
  130. {
  131. $field_name = isset($field_object->field_name) ? $field_object->field_name : $field_object;
  132. if(!isset($types[$field_name]))
  133. {
  134. $field_info = (object)array(
  135. 'name' => $field_name,
  136. 'crud_type' => $this->change_field_type !== null && isset($this->change_field_type[$field_name]) ?
  137. $this->change_field_type[$field_name]->type :
  138. 'string',
  139. 'display_as' => isset($this->display_as[$field_name]) ?
  140. $this->display_as[$field_name] :
  141. ucfirst(str_replace("_"," ",$field_name)),
  142. 'required' => in_array($field_name,$this->required_fields) ? true : false
  143. );
  144. $types[$field_name] = $field_info;
  145. }
  146. }
  147. $this->field_types = $types;
  148. return $this->field_types;
  149. }
  150. public function get_primary_key()
  151. {
  152. return $this->basic_model->get_primary_key();
  153. }
  154. /**
  155. * Get the html input for the specific field with the
  156. * current value
  157. *
  158. * @param object $field_info
  159. * @param string $value
  160. * @return object
  161. */
  162. protected function get_field_input($field_info, $value = null)
  163. {
  164. $real_type = $field_info->crud_type;
  165. $types_array = array(
  166. 'integer',
  167. 'text',
  168. 'true_false',
  169. 'string',
  170. 'date',
  171. 'datetime',
  172. 'enum',
  173. 'set',
  174. 'relation',
  175. 'relation_n_n',
  176. 'upload_file',
  177. 'hidden',
  178. 'password',
  179. 'readonly',
  180. 'dropdown',
  181. 'multiselect'
  182. );
  183. if (in_array($real_type,$types_array)) {
  184. /* A quick way to go to an internal method of type $this->get_{type}_input .
  185. * For example if the real type is integer then we will use the method
  186. * $this->get_integer_input
  187. * */
  188. $field_info->input = $this->{"get_".$real_type."_input"}($field_info,$value);
  189. }
  190. else
  191. {
  192. $field_info->input = $this->get_string_input($field_info,$value);
  193. }
  194. return $field_info;
  195. }
  196. protected function change_list_value($field_info, $value = null)
  197. {
  198. $real_type = $field_info->crud_type;
  199. switch ($real_type) {
  200. case 'hidden':
  201. case 'invisible':
  202. case 'integer':
  203. break;
  204. case 'true_false':
  205. if(isset($this->default_true_false_text[$value]))
  206. $value = $this->default_true_false_text[$value];
  207. break;
  208. case 'string':
  209. $value = $this->character_limiter($value,$this->character_limiter,"...");
  210. break;
  211. case 'text':
  212. $value = $this->character_limiter(strip_tags($value),$this->character_limiter,"...");
  213. break;
  214. case 'date':
  215. if(!empty($value) && $value != '0000-00-00' && $value != '1970-01-01')
  216. {
  217. list($year,$month,$day) = explode("-",$value);
  218. $value = date($this->php_date_format, mktime (0, 0, 0, (int)$month , (int)$day , (int)$year));
  219. }
  220. else
  221. {
  222. $value = '';
  223. }
  224. break;
  225. case 'datetime':
  226. if(!empty($value) && $value != '0000-00-00 00:00:00' && $value != '1970-01-01 00:00:00')
  227. {
  228. list($year,$month,$day) = explode("-",$value);
  229. list($hours,$minutes) = explode(":",substr($value,11));
  230. $value = date($this->php_date_format." - H:i", mktime ((int)$hours , (int)$minutes , 0, (int)$month , (int)$day ,(int)$year));
  231. }
  232. else
  233. {
  234. $value = '';
  235. }
  236. break;
  237. case 'enum':
  238. $value = $this->character_limiter($value,$this->character_limiter,"...");
  239. break;
  240. case 'multiselect':
  241. $value_as_array = array();
  242. foreach(explode(",",$value) as $row_value)
  243. {
  244. $value_as_array[] = array_key_exists($row_value,$field_info->extras) ? $field_info->extras[$row_value] : $row_value;
  245. }
  246. $value = implode(",",$value_as_array);
  247. break;
  248. case 'relation_n_n':
  249. $value = $this->character_limiter(str_replace(',',', ',$value),$this->character_limiter,"...");
  250. break;
  251. case 'password':
  252. $value = '******';
  253. break;
  254. case 'dropdown':
  255. $value = array_key_exists($value,$field_info->extras) ? $field_info->extras[$value] : $value;
  256. break;
  257. case 'upload_file':
  258. if(empty($value))
  259. {
  260. $value = "";
  261. }
  262. else
  263. {
  264. $is_image = !empty($value) &&
  265. ( substr($value,-4) == '.jpg'
  266. || substr($value,-4) == '.png'
  267. || substr($value,-5) == '.jpeg'
  268. || substr($value,-4) == '.gif'
  269. || substr($value,-5) == '.tiff')
  270. ? true : false;
  271. $file_url = base_url().$field_info->extras->upload_path."/$value";
  272. $file_url_anchor = '<a href="'.$file_url.'"';
  273. if($is_image)
  274. {
  275. $file_url_anchor .= ' class="image-thumbnail"><img src="'.$file_url.'" height="50px">';
  276. }
  277. else
  278. {
  279. $file_url_anchor .= ' target="_blank">'.$this->character_limiter($value,$this->character_limiter,'...',true);
  280. }
  281. $file_url_anchor .= '</a>';
  282. $value = $file_url_anchor;
  283. }
  284. break;
  285. default:
  286. $value = $this->character_limiter($value,$this->character_limiter,"...");
  287. break;
  288. }
  289. return $value;
  290. }
  291. /**
  292. * Character Limiter of codeigniter (I just don't want to load the helper )
  293. *
  294. * Limits the string based on the character count. Preserves complete words
  295. * so the character count may not be exactly as specified.
  296. *
  297. * @access public
  298. * @param string
  299. * @param integer
  300. * @param string the end character. Usually an ellipsis
  301. * @return string
  302. */
  303. function character_limiter($str, $n = 500, $end_char = '&#8230;')
  304. {
  305. if (strlen($str) < $n)
  306. {
  307. return $str;
  308. }
  309. // a bit complicated, but faster than preg_replace with \s+
  310. $str = preg_replace('/ {2,}/', ' ', str_replace(array("\r", "\n", "\t", "\x0B", "\x0C"), ' ', $str));
  311. if (strlen($str) <= $n)
  312. {
  313. return $str;
  314. }
  315. $out = '';
  316. foreach (explode(' ', trim($str)) as $val)
  317. {
  318. $out .= $val.' ';
  319. if (strlen($out) >= $n)
  320. {
  321. $out = trim($out);
  322. return (strlen($out) === strlen($str)) ? $out : $out.$end_char;
  323. }
  324. }
  325. }
  326. protected function get_type($db_type)
  327. {
  328. $type = false;
  329. if(!empty($db_type->type))
  330. {
  331. switch ($db_type->type) {
  332. case '1':
  333. case '3':
  334. case 'int':
  335. case 'tinyint':
  336. case 'mediumint':
  337. case 'longint':
  338. if( $db_type->db_type == 'tinyint' && $db_type->db_max_length == 1)
  339. $type = 'true_false';
  340. else
  341. $type = 'integer';
  342. break;
  343. case '254':
  344. case 'string':
  345. case 'enum':
  346. if($db_type->db_type != 'enum')
  347. $type = 'string';
  348. else
  349. $type = 'enum';
  350. break;
  351. case 'set':
  352. if($db_type->db_type != 'set')
  353. $type = 'string';
  354. else
  355. $type = 'set';
  356. break;
  357. case '252':
  358. case 'blob':
  359. case 'text':
  360. case 'mediumtext':
  361. case 'longtext':
  362. $type = 'text';
  363. break;
  364. case '10':
  365. case 'date':
  366. $type = 'date';
  367. break;
  368. case '12':
  369. case 'datetime':
  370. case 'timestamp':
  371. $type = 'datetime';
  372. break;
  373. }
  374. }
  375. return $type;
  376. }
  377. }
  378. // ------------------------------------------------------------------------
  379. /**
  380. * Grocery Model Driver
  381. *
  382. * Drives the model - I'ts so easy like you drive a bicycle :-)
  383. *
  384. * @package grocery CRUD
  385. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  386. * @version 1.3
  387. * @link http://www.grocerycrud.com/documentation
  388. */
  389. class grocery_CRUD_Model_Driver extends grocery_CRUD_Field_Types
  390. {
  391. /**
  392. * @var grocery_CRUD_Model
  393. */
  394. public $basic_model = null;
  395. protected function set_default_Model()
  396. {
  397. $ci = &get_instance();
  398. $ci->load->model('grocery_CRUD_Model');
  399. $this->basic_model = $ci->grocery_CRUD_Model;
  400. }
  401. protected function get_total_results()
  402. {
  403. if(!empty($this->where))
  404. foreach($this->where as $where)
  405. $this->basic_model->where($where[0],$where[1],$where[2]);
  406. if(!empty($this->or_where))
  407. foreach($this->or_where as $or_where)
  408. $this->basic_model->or_where($or_where[0],$or_where[1],$or_where[2]);
  409. if(!empty($this->like))
  410. foreach($this->like as $like)
  411. $this->basic_model->like($like[0],$like[1],$like[2]);
  412. if(!empty($this->or_like))
  413. foreach($this->or_like as $or_like)
  414. $this->basic_model->or_like($or_like[0],$or_like[1],$or_like[2]);
  415. if(!empty($this->having))
  416. foreach($this->having as $having)
  417. $this->basic_model->having($having[0],$having[1],$having[2]);
  418. if(!empty($this->or_having))
  419. foreach($this->or_having as $or_having)
  420. $this->basic_model->or_having($or_having[0],$or_having[1],$or_having[2]);
  421. if(!empty($this->relation))
  422. foreach($this->relation as $relation)
  423. $this->basic_model->join_relation($relation[0],$relation[1],$relation[2]);
  424. if(!empty($this->relation_n_n))
  425. {
  426. $columns = $this->get_columns();
  427. foreach($columns as $column)
  428. {
  429. //Use the relation_n_n ONLY if the column is called . The set_relation_n_n are slow and it will make the table slower without any reason as we don't need those queries.
  430. if(isset($this->relation_n_n[$column->field_name]))
  431. {
  432. $this->basic_model->set_relation_n_n_field($this->relation_n_n[$column->field_name]);
  433. }
  434. }
  435. }
  436. return $this->basic_model->get_total_results();
  437. }
  438. public function set_model($model_name)
  439. {
  440. $ci = &get_instance();
  441. $ci->load->model('grocery_CRUD_Model');
  442. $ci->load->model($model_name);
  443. $temp = explode('/',$model_name);
  444. krsort($temp);
  445. foreach($temp as $t)
  446. {
  447. $real_model_name = $t;
  448. break;
  449. }
  450. $this->basic_model = $ci->$real_model_name;
  451. }
  452. protected function set_ajax_list_queries($state_info = null)
  453. {
  454. if(!empty($state_info->per_page))
  455. {
  456. if(empty($state_info->page) || !is_numeric($state_info->page) )
  457. $this->limit($state_info->per_page);
  458. else
  459. {
  460. $limit_page = ( ($state_info->page-1) * $state_info->per_page );
  461. $this->limit($state_info->per_page, $limit_page);
  462. }
  463. }
  464. if(!empty($state_info->order_by))
  465. {
  466. $this->order_by($state_info->order_by[0],$state_info->order_by[1]);
  467. }
  468. if(!empty($state_info->search))
  469. {
  470. if(!empty($this->relation))
  471. foreach($this->relation as $relation_name => $relation_values)
  472. $temp_relation[$this->_unique_field_name($relation_name)] = $this->_get_field_names_to_search($relation_values);
  473. if($state_info->search->field !== null)
  474. {
  475. if(isset($temp_relation[$state_info->search->field]))
  476. {
  477. if(is_array($temp_relation[$state_info->search->field]))
  478. foreach($temp_relation[$state_info->search->field] as $search_field)
  479. $this->or_like($search_field , $state_info->search->text);
  480. else
  481. $this->like($temp_relation[$state_info->search->field] , $state_info->search->text);
  482. }
  483. elseif(isset($this->relation_n_n[$state_info->search->field]))
  484. {
  485. $escaped_text = $this->basic_model->escape_str($state_info->search->text);
  486. $this->having($state_info->search->field." LIKE '%".$escaped_text."%'");
  487. }
  488. else
  489. {
  490. $this->like($state_info->search->field , $state_info->search->text);
  491. }
  492. }
  493. else
  494. {
  495. $columns = $this->get_columns();
  496. $search_text = $state_info->search->text;
  497. if(!empty($this->where))
  498. foreach($this->where as $where)
  499. $this->basic_model->having($where[0],$where[1],$where[2]);
  500. foreach($columns as $column)
  501. {
  502. if(isset($temp_relation[$column->field_name]))
  503. {
  504. if(is_array($temp_relation[$column->field_name]))
  505. {
  506. foreach($temp_relation[$column->field_name] as $search_field)
  507. {
  508. $this->or_like($search_field, $search_text);
  509. }
  510. }
  511. else
  512. {
  513. $this->or_like($temp_relation[$column->field_name], $search_text);
  514. }
  515. }
  516. elseif(isset($this->relation_n_n[$column->field_name]))
  517. {
  518. //@todo have a where for the relation_n_n statement
  519. }
  520. else
  521. {
  522. $this->or_like($column->field_name, $search_text);
  523. }
  524. }
  525. }
  526. }
  527. }
  528. protected function table_exists($table_name = null)
  529. {
  530. if($this->basic_model->db_table_exists($table_name))
  531. return true;
  532. return false;
  533. }
  534. protected function get_relation_array($relation_info, $primary_key_value = null, $limit = null)
  535. {
  536. list($field_name , $related_table , $related_field_title, $where_clause, $order_by) = $relation_info;
  537. if($primary_key_value !== null)
  538. {
  539. $primary_key = $this->basic_model->get_primary_key($related_table);
  540. //A where clause with the primary key is enough to take the selected key row
  541. $where_clause = array($primary_key => $primary_key_value);
  542. }
  543. $relation_array = $this->basic_model->get_relation_array($field_name , $related_table , $related_field_title, $where_clause, $order_by, $limit);
  544. return $relation_array;
  545. }
  546. protected function get_relation_total_rows($relation_info)
  547. {
  548. list($field_name , $related_table , $related_field_title, $where_clause) = $relation_info;
  549. $relation_array = $this->basic_model->get_relation_total_rows($field_name , $related_table , $related_field_title, $where_clause);
  550. return $relation_array;
  551. }
  552. protected function db_insert_validation()
  553. {
  554. $validation_result = (object)array('success'=>false);
  555. $field_types = $this->get_field_types();
  556. $required_fields = $this->required_fields;
  557. $add_fields = $this->get_add_fields();
  558. if(!empty($required_fields))
  559. {
  560. foreach($add_fields as $add_field)
  561. {
  562. $field_name = $add_field->field_name;
  563. if(!isset($this->validation_rules[$field_name]) && in_array( $field_name, $required_fields) )
  564. {
  565. $this->set_rules( $field_name, $field_types[$field_name]->display_as, 'required');
  566. }
  567. }
  568. }
  569. if(!empty($this->validation_rules))
  570. {
  571. $form_validation = $this->form_validation();
  572. $add_fields = $this->get_add_fields();
  573. foreach($add_fields as $add_field)
  574. {
  575. $field_name = $add_field->field_name;
  576. if(isset($this->validation_rules[$field_name]))
  577. {
  578. $rule = $this->validation_rules[$field_name];
  579. $form_validation->set_rules($rule['field'],$rule['label'],$rule['rules']);
  580. }
  581. }
  582. if($form_validation->run())
  583. {
  584. $validation_result->success = true;
  585. }
  586. else
  587. {
  588. $validation_result->error_message = $form_validation->error_string();
  589. $validation_result->error_fields = $form_validation->_error_array;
  590. }
  591. }
  592. else
  593. {
  594. $validation_result->success = true;
  595. }
  596. return $validation_result;
  597. }
  598. protected function form_validation()
  599. {
  600. if($this->form_validation === null)
  601. {
  602. $this->form_validation = new grocery_CRUD_Form_validation();
  603. $ci = &get_instance();
  604. $ci->load->library('form_validation');
  605. $ci->form_validation = $this->form_validation;
  606. }
  607. return $this->form_validation;
  608. }
  609. protected function db_update_validation()
  610. {
  611. $validation_result = (object)array('success'=>false);
  612. $field_types = $this->get_field_types();
  613. $required_fields = $this->required_fields;
  614. $edit_fields = $this->get_edit_fields();
  615. if(!empty($required_fields))
  616. {
  617. foreach($edit_fields as $edit_field)
  618. {
  619. $field_name = $edit_field->field_name;
  620. if(!isset($this->validation_rules[$field_name]) && in_array( $field_name, $required_fields) )
  621. {
  622. $this->set_rules( $field_name, $field_types[$field_name]->display_as, 'required');
  623. }
  624. }
  625. }
  626. if(!empty($this->validation_rules))
  627. {
  628. $form_validation = $this->form_validation();
  629. $edit_fields = $this->get_edit_fields();
  630. foreach($edit_fields as $edit_field)
  631. {
  632. $field_name = $edit_field->field_name;
  633. if(isset($this->validation_rules[$field_name]))
  634. {
  635. $rule = $this->validation_rules[$field_name];
  636. $form_validation->set_rules($rule['field'],$rule['label'],$rule['rules']);
  637. }
  638. }
  639. if($form_validation->run())
  640. {
  641. $validation_result->success = true;
  642. }
  643. else
  644. {
  645. $validation_result->error_message = $form_validation->error_string();
  646. $validation_result->error_fields = $form_validation->_error_array;
  647. }
  648. }
  649. else
  650. {
  651. $validation_result->success = true;
  652. }
  653. return $validation_result;
  654. }
  655. protected function db_insert($state_info)
  656. {
  657. $validation_result = $this->db_insert_validation();
  658. if($validation_result->success)
  659. {
  660. $post_data = $state_info->unwrapped_data;
  661. $add_fields = $this->get_add_fields();
  662. if($this->callback_insert === null)
  663. {
  664. if($this->callback_before_insert !== null)
  665. {
  666. $callback_return = call_user_func($this->callback_before_insert, $post_data);
  667. if(!empty($callback_return) && is_array($callback_return))
  668. $post_data = $callback_return;
  669. elseif($callback_return === false)
  670. return false;
  671. }
  672. $insert_data = array();
  673. $types = $this->get_field_types();
  674. foreach($add_fields as $num_row => $field)
  675. {
  676. /* If the multiselect or the set is empty then the browser doesn't send an empty array. Instead it sends nothing */
  677. if(isset($types[$field->field_name]->crud_type) && ($types[$field->field_name]->crud_type == 'set' || $types[$field->field_name]->crud_type == 'multiselect') && !isset($post_data[$field->field_name]))
  678. {
  679. $post_data[$field->field_name] = array();
  680. }
  681. if(isset($post_data[$field->field_name]) && !isset($this->relation_n_n[$field->field_name]))
  682. {
  683. if(isset($types[$field->field_name]->db_null) && $types[$field->field_name]->db_null && is_array($post_data[$field->field_name]) && empty($post_data[$field->field_name]))
  684. {
  685. $insert_data[$field->field_name] = null;
  686. }
  687. elseif(isset($types[$field->field_name]->db_null) && $types[$field->field_name]->db_null && $post_data[$field->field_name] === '')
  688. {
  689. $insert_data[$field->field_name] = null;
  690. }
  691. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'date')
  692. {
  693. $insert_data[$field->field_name] = $this->_convert_date_to_sql_date($post_data[$field->field_name]);
  694. }
  695. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'readonly')
  696. {
  697. //This empty if statement is to make sure that a readonly field will never inserted/updated
  698. }
  699. elseif(isset($types[$field->field_name]->crud_type) && ($types[$field->field_name]->crud_type == 'set' || $types[$field->field_name]->crud_type == 'multiselect'))
  700. {
  701. $insert_data[$field->field_name] = !empty($post_data[$field->field_name]) ? implode(',',$post_data[$field->field_name]) : '';
  702. }
  703. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'datetime'){
  704. $insert_data[$field->field_name] = $this->_convert_date_to_sql_date(substr($post_data[$field->field_name],0,10)).
  705. substr($post_data[$field->field_name],10);
  706. }
  707. else
  708. {
  709. $insert_data[$field->field_name] = $post_data[$field->field_name];
  710. }
  711. }
  712. }
  713. $insert_result = $this->basic_model->db_insert($insert_data);
  714. if($insert_result !== false)
  715. {
  716. $insert_primary_key = $insert_result;
  717. }
  718. else
  719. {
  720. return false;
  721. }
  722. if(!empty($this->relation_n_n))
  723. {
  724. foreach($this->relation_n_n as $field_name => $field_info)
  725. {
  726. $relation_data = isset( $post_data[$field_name] ) ? $post_data[$field_name] : array() ;
  727. $this->db_relation_n_n_update($field_info, $relation_data ,$insert_primary_key);
  728. }
  729. }
  730. if($this->callback_after_insert !== null)
  731. {
  732. $callback_return = call_user_func($this->callback_after_insert, $post_data, $insert_primary_key);
  733. if($callback_return === false)
  734. {
  735. return false;
  736. }
  737. }
  738. }else
  739. {
  740. $callback_return = call_user_func($this->callback_insert, $post_data);
  741. if($callback_return === false)
  742. {
  743. return false;
  744. }
  745. }
  746. if(isset($insert_primary_key))
  747. return $insert_primary_key;
  748. else
  749. return true;
  750. }
  751. return false;
  752. }
  753. protected function db_update($state_info)
  754. {
  755. $validation_result = $this->db_update_validation();
  756. $edit_fields = $this->get_edit_fields();
  757. if($validation_result->success)
  758. {
  759. $post_data = $state_info->unwrapped_data;
  760. $primary_key = $state_info->primary_key;
  761. if($this->callback_update === null)
  762. {
  763. if($this->callback_before_update !== null)
  764. {
  765. $callback_return = call_user_func($this->callback_before_update, $post_data, $primary_key);
  766. if(!empty($callback_return) && is_array($callback_return))
  767. {
  768. $post_data = $callback_return;
  769. }
  770. elseif($callback_return === false)
  771. {
  772. return false;
  773. }
  774. }
  775. $update_data = array();
  776. $types = $this->get_field_types();
  777. foreach($edit_fields as $num_row => $field)
  778. {
  779. /* If the multiselect or the set is empty then the browser doesn't send an empty array. Instead it sends nothing */
  780. if(isset($types[$field->field_name]->crud_type) && ($types[$field->field_name]->crud_type == 'set' || $types[$field->field_name]->crud_type == 'multiselect') && !isset($post_data[$field->field_name]))
  781. {
  782. $post_data[$field->field_name] = array();
  783. }
  784. if(isset($post_data[$field->field_name]) && !isset($this->relation_n_n[$field->field_name]))
  785. {
  786. if(isset($types[$field->field_name]->db_null) && $types[$field->field_name]->db_null && is_array($post_data[$field->field_name]) && empty($post_data[$field->field_name]))
  787. {
  788. $update_data[$field->field_name] = null;
  789. }
  790. elseif(isset($types[$field->field_name]->db_null) && $types[$field->field_name]->db_null && $post_data[$field->field_name] === '')
  791. {
  792. $update_data[$field->field_name] = null;
  793. }
  794. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'date')
  795. {
  796. $update_data[$field->field_name] = $this->_convert_date_to_sql_date($post_data[$field->field_name]);
  797. }
  798. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'readonly')
  799. {
  800. //This empty if statement is to make sure that a readonly field will never inserted/updated
  801. }
  802. elseif(isset($types[$field->field_name]->crud_type) && ($types[$field->field_name]->crud_type == 'set' || $types[$field->field_name]->crud_type == 'multiselect'))
  803. {
  804. $update_data[$field->field_name] = !empty($post_data[$field->field_name]) ? implode(',',$post_data[$field->field_name]) : '';
  805. }
  806. elseif(isset($types[$field->field_name]->crud_type) && $types[$field->field_name]->crud_type == 'datetime'){
  807. $update_data[$field->field_name] = $this->_convert_date_to_sql_date(substr($post_data[$field->field_name],0,10)).
  808. substr($post_data[$field->field_name],10);
  809. }
  810. else
  811. {
  812. $update_data[$field->field_name] = $post_data[$field->field_name];
  813. }
  814. }
  815. }
  816. if($this->basic_model->db_update($update_data, $primary_key) === false)
  817. {
  818. return false;
  819. }
  820. if(!empty($this->relation_n_n))
  821. {
  822. foreach($this->relation_n_n as $field_name => $field_info)
  823. {
  824. if ( $this->unset_edit_fields !== null
  825. && is_array($this->unset_edit_fields)
  826. && in_array($field_name,$this->unset_edit_fields)
  827. ) {
  828. continue;
  829. }
  830. $relation_data = isset( $post_data[$field_name] ) ? $post_data[$field_name] : array() ;
  831. $this->db_relation_n_n_update($field_info, $relation_data ,$primary_key);
  832. }
  833. }
  834. if($this->callback_after_update !== null)
  835. {
  836. $callback_return = call_user_func($this->callback_after_update, $post_data, $primary_key);
  837. if($callback_return === false)
  838. {
  839. return false;
  840. }
  841. }
  842. }
  843. else
  844. {
  845. $callback_return = call_user_func($this->callback_update, $post_data, $primary_key);
  846. if($callback_return === false)
  847. {
  848. return false;
  849. }
  850. }
  851. return true;
  852. }
  853. else
  854. {
  855. return false;
  856. }
  857. }
  858. protected function _convert_date_to_sql_date($date)
  859. {
  860. $date = substr($date,0,10);
  861. if(preg_match('/\d{4}-\d{2}-\d{2}/',$date))
  862. {
  863. //If it's already a sql-date don't convert it!
  864. return $date;
  865. }elseif(empty($date))
  866. {
  867. return '';
  868. }
  869. $date_array = preg_split( '/[-\.\/ ]/', $date);
  870. if($this->php_date_format == 'd/m/Y')
  871. {
  872. $sql_date = date('Y-m-d',mktime(0,0,0,$date_array[1],$date_array[0],$date_array[2]));
  873. }
  874. elseif($this->php_date_format == 'm/d/Y')
  875. {
  876. $sql_date = date('Y-m-d',mktime(0,0,0,$date_array[0],$date_array[1],$date_array[2]));
  877. }
  878. else
  879. {
  880. $sql_date = $date;
  881. }
  882. return $sql_date;
  883. }
  884. protected function _get_field_names_to_search(array $relation_values)
  885. {
  886. if(!strstr($relation_values[2],'{'))
  887. return $this->_unique_join_name($relation_values[0]).'.'.$relation_values[2];
  888. else
  889. {
  890. $relation_values[2] = ' '.$relation_values[2].' ';
  891. $temp1 = explode('{',$relation_values[2]);
  892. unset($temp1[0]);
  893. $field_names_array = array();
  894. foreach($temp1 as $field)
  895. list($field_names_array[]) = explode('}',$field);
  896. return $field_names_array;
  897. }
  898. }
  899. protected function _unique_join_name($field_name)
  900. {
  901. return 'j'.substr(md5($field_name),0,8); //This j is because is better for a string to begin with a letter and not a number
  902. }
  903. protected function _unique_field_name($field_name)
  904. {
  905. return 's'.substr(md5($field_name),0,8); //This s is because is better for a string to begin with a letter and not a number
  906. }
  907. protected function db_delete($state_info)
  908. {
  909. $primary_key = $state_info->primary_key;
  910. if($this->callback_delete === null)
  911. {
  912. if($this->callback_before_delete !== null)
  913. {
  914. $callback_return = call_user_func($this->callback_before_delete, $primary_key);
  915. if($callback_return === false)
  916. {
  917. return false;
  918. }
  919. }
  920. if(!empty($this->relation_n_n))
  921. {
  922. foreach($this->relation_n_n as $field_name => $field_info)
  923. {
  924. $this->db_relation_n_n_delete( $field_info, $primary_key );
  925. }
  926. }
  927. $delete_result = $this->basic_model->db_delete($primary_key);
  928. if($delete_result === false)
  929. {
  930. return false;
  931. }
  932. if($this->callback_after_delete !== null)
  933. {
  934. $callback_return = call_user_func($this->callback_after_delete, $primary_key);
  935. if($callback_return === false)
  936. {
  937. return false;
  938. }
  939. }
  940. }
  941. else
  942. {
  943. $callback_return = call_user_func($this->callback_delete, $primary_key);
  944. if($callback_return === false)
  945. {
  946. return false;
  947. }
  948. }
  949. return true;
  950. }
  951. protected function db_relation_n_n_update($field_info, $post_data , $primary_key_value)
  952. {
  953. $this->basic_model->db_relation_n_n_update($field_info, $post_data , $primary_key_value);
  954. }
  955. protected function db_relation_n_n_delete($field_info, $primary_key_value)
  956. {
  957. $this->basic_model->db_relation_n_n_delete($field_info, $primary_key_value);
  958. }
  959. protected function get_list()
  960. {
  961. if(!empty($this->order_by))
  962. $this->basic_model->order_by($this->order_by[0],$this->order_by[1]);
  963. if(!empty($this->where))
  964. foreach($this->where as $where)
  965. $this->basic_model->where($where[0],$where[1],$where[2]);
  966. if(!empty($this->or_where))
  967. foreach($this->or_where as $or_where)
  968. $this->basic_model->or_where($or_where[0],$or_where[1],$or_where[2]);
  969. if(!empty($this->like))
  970. foreach($this->like as $like)
  971. $this->basic_model->like($like[0],$like[1],$like[2]);
  972. if(!empty($this->or_like))
  973. foreach($this->or_like as $or_like)
  974. $this->basic_model->or_like($or_like[0],$or_like[1],$or_like[2]);
  975. if(!empty($this->having))
  976. foreach($this->having as $having)
  977. $this->basic_model->having($having[0],$having[1],$having[2]);
  978. if(!empty($this->or_having))
  979. foreach($this->or_having as $or_having)
  980. $this->basic_model->or_having($or_having[0],$or_having[1],$or_having[2]);
  981. if(!empty($this->relation))
  982. foreach($this->relation as $relation)
  983. $this->basic_model->join_relation($relation[0],$relation[1],$relation[2]);
  984. if(!empty($this->relation_n_n))
  985. {
  986. $columns = $this->get_columns();
  987. foreach($columns as $column)
  988. {
  989. //Use the relation_n_n ONLY if the column is called . The set_relation_n_n are slow and it will make the table slower without any reason as we don't need those queries.
  990. if(isset($this->relation_n_n[$column->field_name]))
  991. {
  992. $this->basic_model->set_relation_n_n_field($this->relation_n_n[$column->field_name]);
  993. }
  994. }
  995. }
  996. if($this->theme_config['crud_paging'] === true)
  997. {
  998. if($this->limit === null)
  999. {
  1000. $default_per_page = $this->config->default_per_page;
  1001. if(is_numeric($default_per_page) && $default_per_page >1)
  1002. {
  1003. $this->basic_model->limit($default_per_page);
  1004. }
  1005. else
  1006. {
  1007. $this->basic_model->limit(10);
  1008. }
  1009. }
  1010. else
  1011. {
  1012. $this->basic_model->limit($this->limit[0],$this->limit[1]);
  1013. }
  1014. }
  1015. $results = $this->basic_model->get_list();
  1016. return $results;
  1017. }
  1018. protected function get_edit_values($primary_key_value)
  1019. {
  1020. $values = $this->basic_model->get_edit_values($primary_key_value);
  1021. if(!empty($this->relation_n_n))
  1022. {
  1023. foreach($this->relation_n_n as $field_name => $field_info)
  1024. {
  1025. $values->$field_name = $this->get_relation_n_n_selection_array($primary_key_value, $field_info);
  1026. }
  1027. }
  1028. return $values;
  1029. }
  1030. protected function get_relation_n_n_selection_array($primary_key_value, $field_info)
  1031. {
  1032. return $this->basic_model->get_relation_n_n_selection_array($primary_key_value, $field_info);
  1033. }
  1034. protected function get_relation_n_n_unselected_array($field_info, $selected_values)
  1035. {
  1036. return $this->basic_model->get_relation_n_n_unselected_array($field_info, $selected_values);
  1037. }
  1038. protected function set_basic_db_table($table_name = null)
  1039. {
  1040. $this->basic_model->set_basic_table($table_name);
  1041. }
  1042. protected function upload_file($state_info)
  1043. {
  1044. if(isset($this->upload_fields[$state_info->field_name]) )
  1045. {
  1046. if($this->callback_upload === null)
  1047. {
  1048. if($this->callback_before_upload !== null)
  1049. {
  1050. $callback_before_upload_response = call_user_func($this->callback_before_upload, $_FILES, $this->upload_fields[$state_info->field_name]);
  1051. if($callback_before_upload_response === false)
  1052. return false;
  1053. elseif(is_string($callback_before_upload_response))
  1054. return $callback_before_upload_response;
  1055. }
  1056. $upload_info = $this->upload_fields[$state_info->field_name];
  1057. header('Pragma: no-cache');
  1058. header('Cache-Control: private, no-cache');
  1059. header('Content-Disposition: inline; filename="files.json"');
  1060. header('X-Content-Type-Options: nosniff');
  1061. header('Access-Control-Allow-Origin: *');
  1062. header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
  1063. header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');
  1064. $allowed_files = $this->config->file_upload_allow_file_types;
  1065. $reg_exp = '/(\\.|\\/)('.$allowed_files.')$/i';
  1066. $max_file_size_ui = $this->config->file_upload_max_file_size;
  1067. $max_file_size_bytes = $this->_convert_bytes_ui_to_bytes($max_file_size_ui);
  1068. $options = array(
  1069. 'upload_dir' => $upload_info->upload_path.'/',
  1070. 'param_name' => $this->_unique_field_name($state_info->field_name),
  1071. 'upload_url' => base_url().$upload_info->upload_path.'/',
  1072. 'accept_file_types' => $reg_exp,
  1073. 'max_file_size' => $max_file_size_bytes
  1074. );
  1075. $upload_handler = new UploadHandler($options);
  1076. $upload_handler->default_config_path = $this->default_config_path;
  1077. $uploader_response = $upload_handler->post();
  1078. if(is_array($uploader_response))
  1079. {
  1080. foreach($uploader_response as &$response)
  1081. {
  1082. unset($response->delete_url);
  1083. unset($response->delete_type);
  1084. }
  1085. }
  1086. if($this->callback_after_upload !== null)
  1087. {
  1088. $callback_after_upload_response = call_user_func($this->callback_after_upload, $uploader_response , $this->upload_fields[$state_info->field_name] , $_FILES );
  1089. if($callback_after_upload_response === false)
  1090. return false;
  1091. elseif(is_string($callback_after_upload_response))
  1092. return $callback_after_upload_response;
  1093. elseif(is_array($callback_after_upload_response))
  1094. $uploader_response = $callback_after_upload_response;
  1095. }
  1096. return $uploader_response;
  1097. }
  1098. else
  1099. {
  1100. $upload_response = call_user_func($this->callback_upload, $_FILES, $this->upload_fields[$state_info->field_name] );
  1101. if($upload_response === false)
  1102. {
  1103. return false;
  1104. }
  1105. else
  1106. {
  1107. return $upload_response;
  1108. }
  1109. }
  1110. }
  1111. else
  1112. {
  1113. return false;
  1114. }
  1115. }
  1116. protected function delete_file($state_info)
  1117. {
  1118. if(isset($state_info->field_name) && isset($this->upload_fields[$state_info->field_name]))
  1119. {
  1120. $upload_info = $this->upload_fields[$state_info->field_name];
  1121. if(file_exists("{$upload_info->upload_path}/{$state_info->file_name}"))
  1122. {
  1123. if( unlink("{$upload_info->upload_path}/{$state_info->file_name}") )
  1124. {
  1125. $this->basic_model->db_file_delete($state_info->field_name, $state_info->file_name);
  1126. return true;
  1127. }
  1128. else
  1129. {
  1130. return false;
  1131. }
  1132. }
  1133. else
  1134. {
  1135. $this->basic_model->db_file_delete($state_info->field_name, $state_info->file_name);
  1136. return true;
  1137. }
  1138. }
  1139. else
  1140. {
  1141. return false;
  1142. }
  1143. }
  1144. protected function ajax_relation($state_info)
  1145. {
  1146. if(!isset($this->relation[$state_info->field_name]))
  1147. return false;
  1148. list($field_name, $related_table, $related_field_title, $where_clause, $order_by) = $this->relation[$state_info->field_name];
  1149. return $this->basic_model->get_ajax_relation_array($state_info->search, $field_name, $related_table, $related_field_title, $where_clause, $order_by);
  1150. }
  1151. }
  1152. /**
  1153. * PHP grocery CRUD
  1154. *
  1155. * LICENSE
  1156. *
  1157. * Grocery CRUD is released with dual licensing, using the GPL v3 (license-gpl3.txt) and the MIT license (license-mit.txt).
  1158. * You don't have to do anything special to choose one license or the other and you don't have to notify anyone which license you are using.
  1159. * Please see the corresponding license file for details of these licenses.
  1160. * You are free to use, modify and distribute this software, but all copyright information must remain.
  1161. *
  1162. * @package grocery CRUD
  1163. * @copyright Copyright (c) 2010 through 2012, John Skoumbourdis
  1164. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  1165. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  1166. */
  1167. // ------------------------------------------------------------------------
  1168. /**
  1169. * PHP grocery Layout
  1170. *
  1171. * Here you manage all the HTML Layout
  1172. *
  1173. * @package grocery CRUD
  1174. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  1175. * @version 1.3
  1176. */
  1177. class grocery_CRUD_Layout extends grocery_CRUD_Model_Driver
  1178. {
  1179. private $theme_path = null;
  1180. private $views_as_string = '';
  1181. private $echo_and_die = false;
  1182. protected $theme = null;
  1183. protected $default_true_false_text = array('inactive' , 'active');
  1184. protected $css_files = array();
  1185. protected $js_files = array();
  1186. protected function set_basic_Layout()
  1187. {
  1188. if(!file_exists($this->theme_path.$this->theme.'/views/list_template.php'))
  1189. {
  1190. throw new Exception('The template does not exist. Please check your files and try again.', 12);
  1191. die();
  1192. }
  1193. }
  1194. protected function showList($ajax = false, $state_info = null)
  1195. {
  1196. $data = $this->get_common_data();
  1197. $data->order_by = $this->order_by;
  1198. $data->types = $this->get_field_types();
  1199. $data->list = $this->get_list();
  1200. $data->list = $this->change_list($data->list , $data->types);
  1201. $data->list = $this->change_list_add_actions($data->list);
  1202. $data->total_results = $this->get_total_results();
  1203. $data->columns = $this->get_columns();
  1204. $data->success_message = $this->get_success_message_at_list($state_info);
  1205. $data->primary_key = $this->get_primary_key();
  1206. $data->add_url = $this->getAddUrl();
  1207. $data->edit_url = $this->getEditUrl();
  1208. $data->delete_url = $this->getDeleteUrl();
  1209. $data->ajax_list_url = $this->getAjaxListUrl();
  1210. $data->ajax_list_info_url = $this->getAjaxListInfoUrl();
  1211. $data->export_url = $this->getExportToExcelUrl();
  1212. $data->print_url = $this->getPrintUrl();
  1213. $data->actions = $this->actions;
  1214. $data->unique_hash = $this->get_method_hash();
  1215. $data->order_by = $this->order_by;
  1216. $data->unset_add = $this->unset_add;
  1217. $data->unset_edit = $this->unset_edit;
  1218. $data->unset_delete = $this->unset_delete;
  1219. $data->unset_export = $this->unset_export;
  1220. $data->unset_print = $this->unset_print;
  1221. $default_per_page = $this->config->default_per_page;
  1222. $data->paging_options = array('10','25','50','100');
  1223. $data->default_per_page = is_numeric($default_per_page) && $default_per_page >1 && in_array($default_per_page,$data->paging_options)? $default_per_page : 25;
  1224. if($data->list === false)
  1225. {
  1226. throw new Exception('It is impossible to get data. Please check your model and try again.', 13);
  1227. $data->list = array();
  1228. }
  1229. foreach($data->list as $num_row => $row)
  1230. {
  1231. $data->list[$num_row]->edit_url = $data->edit_url.'/'.$row->{$data->primary_key};
  1232. $data->list[$num_row]->delete_url = $data->delete_url.'/'.$row->{$data->primary_key};
  1233. }
  1234. if(!$ajax)
  1235. {
  1236. $data->list_view = $this->_theme_view('list.php',$data,true);
  1237. $this->_theme_view('list_template.php',$data);
  1238. }
  1239. else
  1240. {
  1241. $this->set_echo_and_die();
  1242. $this->_theme_view('list.php',$data);
  1243. }
  1244. }
  1245. protected function exportToExcel($state_info = null)
  1246. {
  1247. $data = $this->get_common_data();
  1248. $data->order_by = $this->order_by;
  1249. $data->types = $this->get_field_types();
  1250. $data->list = $this->get_list();
  1251. $data->list = $this->change_list($data->list , $data->types);
  1252. $data->list = $this->change_list_add_actions($data->list);
  1253. $data->total_results = $this->get_total_results();
  1254. $data->columns = $this->get_columns();
  1255. $data->primary_key = $this->get_primary_key();
  1256. @ob_end_clean();
  1257. $this->_export_to_excel($data);
  1258. }
  1259. protected function _export_to_excel($data)
  1260. {
  1261. /**
  1262. * No need to use an external library here. The only bad thing without using external library is that Microsoft Excel is complaining
  1263. * that the file is in a different format than specified by the file extension. If you press "Yes" everything will be just fine.
  1264. * */
  1265. $string_to_export = "";
  1266. foreach($data->columns as $column){
  1267. $string_to_export .= $column->display_as."\t";
  1268. }
  1269. $string_to_export .= "\n";
  1270. foreach($data->list as $num_row => $row){
  1271. foreach($data->columns as $column){
  1272. $string_to_export .= $this->_trim_export_string($row->{$column->field_name})."\t";
  1273. }
  1274. $string_to_export .= "\n";
  1275. }
  1276. // Convert to UTF-16LE and Prepend BOM
  1277. $string_to_export = "\xFF\xFE" .mb_convert_encoding($string_to_export, 'UTF-16LE', 'UTF-8');
  1278. $filename = "export-".date("Y-m-d_H:i:s").".xls";
  1279. header('Content-type: application/vnd.ms-excel;charset=UTF-16LE');
  1280. header('Content-Disposition: attachment; filename='.$filename);
  1281. header("Cache-Control: no-cache");
  1282. echo $string_to_export;
  1283. die();
  1284. }
  1285. protected function print_webpage($state_info = null)
  1286. {
  1287. $data = $this->get_common_data();
  1288. $data->order_by = $this->order_by;
  1289. $data->types = $this->get_field_types();
  1290. $data->list = $this->get_list();
  1291. $data->list = $this->change_list($data->list , $data->types);
  1292. $data->list = $this->change_list_add_actions($data->list);
  1293. $data->total_results = $this->get_total_results();
  1294. $data->columns = $this->get_columns();
  1295. $data->primary_key = $this->get_primary_key();
  1296. @ob_end_clean();
  1297. $this->_print_webpage($data);
  1298. }
  1299. protected function _print_webpage($data)
  1300. {
  1301. $string_to_print = "<meta charset=\"utf-8\" /><style type=\"text/css\" >
  1302. #print-table{ color: #000; background: #fff; font-family: Verdana,Tahoma,Helvetica,sans-serif; font-size: 13px;}
  1303. #print-table table tr td, #print-table table tr th{ border: 1px solid black; border-bottom: none; border-right: none; padding: 4px 8px 4px 4px}
  1304. #print-table table{ border-bottom: 1px solid black; border-right: 1px solid black}
  1305. #print-table table tr th{text-align: left;background: #ddd}
  1306. #print-table table tr:nth-child(odd){background: #eee}
  1307. </style>";
  1308. $string_to_print .= "<div id='print-table'>";
  1309. $string_to_print .= '<table width="100%" cellpadding="0" cellspacing="0" ><tr>';
  1310. foreach($data->columns as $column){
  1311. $string_to_print .= "<th>".$column->display_as."</th>";
  1312. }
  1313. $string_to_print .= "</tr>";
  1314. foreach($data->list as $num_row => $row){
  1315. $string_to_print .= "<tr>";
  1316. foreach($data->columns as $column){
  1317. $string_to_print .= "<td>".$this->_trim_print_string($row->{$column->field_name})."</td>";
  1318. }
  1319. $string_to_print .= "</tr>";
  1320. }
  1321. $string_to_print .= "</table></div>";
  1322. echo $string_to_print;
  1323. die();
  1324. }
  1325. protected function _trim_export_string($value)
  1326. {
  1327. $value = str_replace(array("&nbsp;","&amp;","&gt;","&lt;"),array(" ","&",">","<"),$value);
  1328. return strip_tags(str_replace(array("\t","\n","\r"),"",$value));
  1329. }
  1330. protected function _trim_print_string($value)
  1331. {
  1332. $value = str_replace(array("&nbsp;","&amp;","&gt;","&lt;"),array(" ","&",">","<"),$value);
  1333. //If the value has only spaces and nothing more then add the whitespace html character
  1334. if(str_replace(" ","",$value) == "")
  1335. $value = "&nbsp;";
  1336. return strip_tags($value);
  1337. }
  1338. protected function set_echo_and_die()
  1339. {
  1340. $this->echo_and_die = true;
  1341. }
  1342. protected function unset_echo_and_die()
  1343. {
  1344. $this->echo_and_die = false;
  1345. }
  1346. protected function showListInfo()
  1347. {
  1348. $this->set_echo_and_die();
  1349. $total_results = (int)$this->get_total_results();
  1350. @ob_end_clean();
  1351. echo json_encode(array('total_results' => $total_results));
  1352. die();
  1353. }
  1354. protected function change_list_add_actions($list)
  1355. {
  1356. if(empty($this->actions))
  1357. return $list;
  1358. $primary_key = $this->get_primary_key();
  1359. foreach($list as $num_row => $row)
  1360. {
  1361. $actions_urls = array();
  1362. foreach($this->actions as $unique_id => $action)
  1363. {
  1364. if(!empty($action->url_callback))
  1365. {
  1366. $actions_urls[$unique_id] = call_user_func($action->url_callback, $row->$primary_key, $row);
  1367. }
  1368. else
  1369. {
  1370. $actions_urls[$unique_id] =
  1371. $action->url_has_http ?
  1372. $action->link_url.$row->$primary_key :
  1373. site_url($action->link_url.'/'.$row->$primary_key);
  1374. }
  1375. }
  1376. $row->action_urls = $actions_urls;
  1377. }
  1378. return $list;
  1379. }
  1380. protected function change_list($list,$types)
  1381. {
  1382. $primary_key = $this->get_primary_key();
  1383. $has_callbacks = !empty($this->callback_column) ? true : false;
  1384. $output_columns = $this->get_columns();
  1385. foreach($list as $num_row => $row)
  1386. {
  1387. foreach($output_columns as $column)
  1388. {
  1389. $field_name = $column->field_name;
  1390. $field_value = isset( $row->{$column->field_name} ) ? $row->{$column->field_name} : null;
  1391. if( $has_callbacks && isset($this->callback_column[$field_name]) )
  1392. $list[$num_row]->$field_name = call_user_func($this->callback_column[$field_name], $field_value, $row);
  1393. elseif(isset($types[$field_name]))
  1394. $list[$num_row]->$field_name = $this->change_list_value($types[$field_name] , $field_value);
  1395. else
  1396. $list[$num_row]->$field_name = $field_value;
  1397. }
  1398. }
  1399. return $list;
  1400. }
  1401. protected function showAddForm()
  1402. {
  1403. $this->set_js($this->default_javascript_path.'/'.grocery_CRUD::JQUERY);
  1404. $data = $this->get_common_data();
  1405. $data->types = $this->get_field_types();
  1406. $data->list_url = $this->getListUrl();
  1407. $data->insert_url = $this->getInsertUrl();
  1408. $data->validation_url = $this->getValidationInsertUrl();
  1409. $data->input_fields = $this->get_add_input_fields();
  1410. $data->fields = $this->get_add_fields();
  1411. $data->hidden_fields = $this->get_add_hidden_fields();
  1412. $data->unset_back_to_list = $this->unset_back_to_list;
  1413. $this->_theme_view('add.php',$data);
  1414. $this->_inline_js("var js_date_format = '".$this->js_date_format."';");
  1415. }
  1416. protected function showEditForm($state_info)
  1417. {
  1418. $this->set_js($this->default_javascript_path.'/'.grocery_CRUD::JQUERY);
  1419. $data = $this->get_common_data();
  1420. $data->types = $this->get_field_types();
  1421. $data->field_values = $this->get_edit_values($state_info->primary_key);
  1422. $data->add_url = $this->getAddUrl();
  1423. $data->list_url = $this->getListUrl();
  1424. $data->update_url = $this->getUpdateUrl($state_info);
  1425. $data->delete_url = $this->getDeleteUrl($state_info);
  1426. $data->input_fields = $this->get_edit_input_fields($data->field_values);
  1427. $data->fields = $this->get_edit_fields();
  1428. $data->hidden_fields = $this->get_edit_hidden_fields();
  1429. $data->unset_back_to_list = $this->unset_back_to_list;
  1430. $data->validation_url = $this->getValidationUpdateUrl($state_info->primary_key);
  1431. $this->_theme_view('edit.php',$data);
  1432. $this->_inline_js("var js_date_format = '".$this->js_date_format."';");
  1433. }
  1434. protected function delete_layout($delete_result = true)
  1435. {
  1436. @ob_end_clean();
  1437. if($delete_result === false)
  1438. {
  1439. $error_message = '<p>'.$this->l('delete_error_message').'</p>';
  1440. echo json_encode(array('success' => $delete_result ,'error_message' => $error_message));
  1441. }
  1442. else
  1443. {
  1444. $success_message = '<p>'.$this->l('delete_success_message').'</p>';
  1445. echo json_encode(array('success' => true , 'success_message' => $success_message));
  1446. }
  1447. $this->set_echo_and_die();
  1448. }
  1449. protected function get_success_message_at_list($field_info = null)
  1450. {
  1451. if($field_info !== null && isset($field_info->success_message) && $field_info->success_message)
  1452. {
  1453. if(!empty($field_info->primary_key) && !$this->unset_edit)
  1454. {
  1455. return $this->l('insert_success_message')." <a href='".$this->getEditUrl($field_info->primary_key)."'>".$this->l('form_edit')." {$this->subject}</a> ";
  1456. }
  1457. else
  1458. {
  1459. return $this->l('insert_success_message');
  1460. }
  1461. }
  1462. else
  1463. {
  1464. return null;
  1465. }
  1466. }
  1467. protected function insert_layout($insert_result = false)
  1468. {
  1469. @ob_end_clean();
  1470. if($insert_result === false)
  1471. {
  1472. echo json_encode(array('success' => false));
  1473. }
  1474. else
  1475. {
  1476. $success_message = '<p>'.$this->l('insert_success_message');
  1477. if(!$this->unset_back_to_list && !empty($insert_result) && !$this->unset_edit)
  1478. {
  1479. $success_message .= " <a href='".$this->getEditUrl($insert_result)."'>".$this->l('form_edit')." {$this->subject}</a> ".$this->l('form_or');
  1480. }
  1481. if(!$this->unset_back_to_list)
  1482. {
  1483. $success_message .= " <a href='".$this->getListUrl()."'>".$this->l('form_go_back_to_list')."</a>";
  1484. }
  1485. $success_message .= '</p>';
  1486. echo "<textarea>".json_encode(array(
  1487. 'success' => true ,
  1488. 'insert_primary_key' => $insert_result,
  1489. 'success_message' => $success_message,
  1490. 'success_list_url' => $this->getListSuccessUrl($insert_result)
  1491. ))."</textarea>";
  1492. }
  1493. $this->set_echo_and_die();
  1494. }
  1495. protected function validation_layout($validation_result)
  1496. {
  1497. @ob_end_clean();
  1498. echo "<textarea>".json_encode($validation_result)."</textarea>";
  1499. $this->set_echo_and_die();
  1500. }
  1501. protected function upload_layout($upload_result, $field_name)
  1502. {
  1503. @ob_end_clean();
  1504. if($upload_result !== false && !is_string($upload_result) && empty($upload_result[0]->error))
  1505. {
  1506. echo json_encode(
  1507. (object)array(
  1508. 'success' => true,
  1509. 'files' => $upload_result
  1510. ));
  1511. }
  1512. else
  1513. {
  1514. $result = (object)array('success' => false);
  1515. if(is_string($upload_result))
  1516. $result->message = $upload_result;
  1517. if(!empty($upload_result[0]->error))
  1518. $result->message = $upload_result[0]->error;
  1519. echo json_encode($result);
  1520. }
  1521. $this->set_echo_and_die();
  1522. }
  1523. protected function delete_file_layout($upload_result)
  1524. {
  1525. @ob_end_clean();
  1526. if($upload_result !== false)
  1527. {
  1528. echo json_encode( (object)array( 'success' => true ) );
  1529. }
  1530. else
  1531. {
  1532. echo json_encode((object)array('success' => false));
  1533. }
  1534. $this->set_echo_and_die();
  1535. }
  1536. public function set_css($css_file)
  1537. {
  1538. $this->css_files[sha1($css_file)] = base_url().$css_file;
  1539. }
  1540. public function set_js($js_file)
  1541. {
  1542. $this->js_files[sha1($js_file)] = base_url().$js_file;
  1543. }
  1544. public function get_css_files()
  1545. {
  1546. return $this->css_files;
  1547. }
  1548. public function get_js_files()
  1549. {
  1550. return $this->js_files;
  1551. }
  1552. protected function get_layout()
  1553. {
  1554. $js_files = $this->get_js_files();
  1555. $css_files = $this->get_css_files();
  1556. if($this->unset_jquery)
  1557. unset($js_files[sha1($this->default_javascript_path.'/'.grocery_CRUD::JQUERY)]);
  1558. if($this->unset_jquery_ui)
  1559. {
  1560. unset($css_files[sha1($this->default_css_path.'/ui/simple/'.grocery_CRUD::JQUERY_UI_CSS)]);
  1561. unset($js_files[sha1($this->default_javascript_path.'/jquery_plugins/ui/'.grocery_CRUD::JQUERY_UI_JS)]);
  1562. }
  1563. if($this->echo_and_die === false)
  1564. {
  1565. /** Initialize JavaScript variables */
  1566. $js_vars = array(
  1567. 'default_javascript_path' => base_url().$this->default_javascript_path,
  1568. 'default_css_path' => base_url().$this->default_css_path,
  1569. 'default_texteditor_path' => base_url().$this->default_texteditor_path,
  1570. 'default_theme_path' => base_url().$this->default_theme_path,
  1571. 'base_url' => base_url()
  1572. );
  1573. $this->_add_js_vars($js_vars);
  1574. return (object)array('output' => $this->views_as_string, 'js_files' => $js_files, 'css_files' => $css_files);
  1575. }
  1576. elseif($this->echo_and_die === true)
  1577. {
  1578. echo $this->views_as_string;
  1579. die();
  1580. }
  1581. }
  1582. protected function update_layout($update_result = false, $state_info = null)
  1583. {
  1584. @ob_end_clean();
  1585. if($update_result === false)
  1586. {
  1587. echo json_encode(array('success' => $update_result));
  1588. }
  1589. else
  1590. {
  1591. $success_message = '<p>'.$this->l('update_success_message');
  1592. if(!$this->unset_back_to_list)
  1593. {
  1594. $success_message .= " <a href='".$this->getListUrl()."'>".$this->l('form_go_back_to_list')."</a>";
  1595. }
  1596. $success_message .= '</p>';
  1597. /* The textarea is only because of a BUG of the jquery form plugin with the combination of multipart forms */
  1598. echo "<textarea>".json_encode(array(
  1599. 'success' => true ,
  1600. 'insert_primary_key' => $update_result,
  1601. 'success_message' => $success_message,
  1602. 'success_list_url' => $this->getListSuccessUrl($state_info->primary_key)
  1603. ))."</textarea>";
  1604. }
  1605. $this->set_echo_and_die();
  1606. }
  1607. protected function get_integer_input($field_info,$value)
  1608. {
  1609. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.numeric.min.js');
  1610. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.numeric.config.js');
  1611. $extra_attributes = '';
  1612. if(!empty($field_info->db_max_length))
  1613. $extra_attributes .= "maxlength='{$field_info->db_max_length}'";
  1614. $input = "<input id='field-{$field_info->name}' name='{$field_info->name}' type='text' value='$value' class='numeric' $extra_attributes />";
  1615. return $input;
  1616. }
  1617. protected function get_true_false_input($field_info,$value)
  1618. {
  1619. $this->set_css($this->default_css_path.'/jquery_plugins/uniform/uniform.default.css');
  1620. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.uniform.min.js');
  1621. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.uniform.config.js');
  1622. $value_is_null = empty($value) && $value !== '0' && $value !== 0 ? true : false;
  1623. $input = "<div class='pretty-radio-buttons'>";
  1624. $checked = $value === '1' || ($value_is_null && $field_info->default === '1') ? "checked = 'checked'" : "";
  1625. $input .= "<label><input id='field-{$field_info->name}-true' class='radio-uniform' type='radio' name='{$field_info->name}' value='1' $checked /> ".$this->default_true_false_text[1]."</label> ";
  1626. $checked = $value === '0' || ($value_is_null && $field_info->default === '0') ? "checked = 'checked'" : "";
  1627. $input .= "<label><input id='field-{$field_info->name}-false' class='radio-uniform' type='radio' name='{$field_info->name}' value='0' $checked /> ".$this->default_true_false_text[0]."</label>";
  1628. $input .= "</div>";
  1629. return $input;
  1630. }
  1631. protected function get_string_input($field_info,$value)
  1632. {
  1633. $value = !is_string($value) ? '' : str_replace('"',"&quot;",$value);
  1634. $extra_attributes = '';
  1635. if(!empty($field_info->db_max_length))
  1636. $extra_attributes .= "maxlength='{$field_info->db_max_length}'";
  1637. $input = "<input id='field-{$field_info->name}' name='{$field_info->name}' type='text' value=\"$value\" $extra_attributes />";
  1638. return $input;
  1639. }
  1640. protected function get_text_input($field_info,$value)
  1641. {
  1642. if($field_info->extras == 'text_editor')
  1643. {
  1644. $editor = $this->config->default_text_editor;
  1645. switch ($editor) {
  1646. case 'ckeditor':
  1647. $this->set_js($this->default_texteditor_path.'/ckeditor/ckeditor.js');
  1648. $this->set_js($this->default_texteditor_path.'/ckeditor/adapters/jquery.js');
  1649. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.ckeditor.config.js');
  1650. break;
  1651. case 'tinymce':
  1652. $this->set_js($this->default_texteditor_path.'/tiny_mce/jquery.tinymce.js');
  1653. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.tine_mce.config.js');
  1654. break;
  1655. case 'markitup':
  1656. $this->set_css($this->default_texteditor_path.'/markitup/skins/markitup/style.css');
  1657. $this->set_css($this->default_texteditor_path.'/markitup/sets/default/style.css');
  1658. $this->set_js($this->default_texteditor_path.'/markitup/jquery.markitup.js');
  1659. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.markitup.config.js');
  1660. break;
  1661. }
  1662. $class_name = $this->config->text_editor_type == 'minimal' ? 'mini-texteditor' : 'texteditor';
  1663. $input = "<textarea id='field-{$field_info->name}' name='{$field_info->name}' class='$class_name' >$value</textarea>";
  1664. }
  1665. else
  1666. {
  1667. $input = "<textarea id='field-{$field_info->name}' name='{$field_info->name}'>$value</textarea>";
  1668. }
  1669. return $input;
  1670. }
  1671. protected function get_datetime_input($field_info,$value)
  1672. {
  1673. $this->set_css($this->default_css_path.'/ui/simple/'.grocery_CRUD::JQUERY_UI_CSS);
  1674. $this->set_css($this->default_css_path.'/jquery_plugins/jquery.ui.datetime.css');
  1675. $this->set_css($this->default_css_path.'/jquery_plugins/jquery-ui-timepicker-addon.css');
  1676. $this->set_js($this->default_javascript_path.'/jquery_plugins/ui/'.grocery_CRUD::JQUERY_UI_JS);
  1677. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery-ui-timepicker-addon.min.js');
  1678. if($this->language !== 'english')
  1679. {
  1680. include($this->default_config_path.'/language_alias.php');
  1681. if(array_key_exists($this->language, $language_alias))
  1682. {
  1683. $i18n_date_js_file = $this->default_javascript_path.'/jquery_plugins/ui/i18n/datepicker/jquery.ui.datepicker-'.$language_alias[$this->language].'.js';
  1684. if(file_exists($i18n_date_js_file))
  1685. {
  1686. $this->set_js($i18n_date_js_file);
  1687. }
  1688. $i18n_datetime_js_file = $this->default_javascript_path.'/jquery_plugins/ui/i18n/timepicker/jquery-ui-timepicker-'.$language_alias[$this->language].'.js';
  1689. if(file_exists($i18n_datetime_js_file))
  1690. {
  1691. $this->set_js($i18n_datetime_js_file);
  1692. }
  1693. }
  1694. }
  1695. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery-ui-timepicker-addon.config.js');
  1696. if(!empty($value) && $value != '0000-00-00 00:00:00' && $value != '1970-01-01 00:00:00'){
  1697. list($year,$month,$day) = explode('-',substr($value,0,10));
  1698. $date = date($this->php_date_format, mktime(0,0,0,$month,$day,$year));
  1699. $datetime = $date.substr($value,10);
  1700. }
  1701. else
  1702. {
  1703. $datetime = '';
  1704. }
  1705. $input = "<input id='field-{$field_info->name}' name='{$field_info->name}' type='text' value='$datetime' maxlength='19' class='datetime-input' />
  1706. <a class='datetime-input-clear' tabindex='-1'>".$this->l('form_button_clear')."</a>
  1707. ({$this->ui_date_format}) hh:mm:ss";
  1708. return $input;
  1709. }
  1710. protected function get_hidden_input($field_info,$value)
  1711. {
  1712. if($field_info->extras !== null && $field_info->extras != false)
  1713. $value = $field_info->extras;
  1714. $input = "<input id='field-{$field_info->name}' type='hidden' name='{$field_info->name}' value='$value' />";
  1715. return $input;
  1716. }
  1717. protected function get_password_input($field_info,$value)
  1718. {
  1719. $value = !is_string($value) ? '' : $value;
  1720. $extra_attributes = '';
  1721. if(!empty($field_info->db_max_length))
  1722. $extra_attributes .= "maxlength='{$field_info->db_max_length}'";
  1723. $input = "<input id='field-{$field_info->name}' name='{$field_info->name}' type='password' value='$value' $extra_attributes />";
  1724. return $input;
  1725. }
  1726. protected function get_date_input($field_info,$value)
  1727. {
  1728. $this->set_css($this->default_css_path.'/ui/simple/'.grocery_CRUD::JQUERY_UI_CSS);
  1729. $this->set_js($this->default_javascript_path.'/jquery_plugins/ui/'.grocery_CRUD::JQUERY_UI_JS);
  1730. if($this->language !== 'english')
  1731. {
  1732. include($this->default_config_path.'/language_alias.php');
  1733. if(array_key_exists($this->language, $language_alias))
  1734. {
  1735. $i18n_date_js_file = $this->default_javascript_path.'/jquery_plugins/ui/i18n/datepicker/jquery.ui.datepicker-'.$language_alias[$this->language].'.js';
  1736. if(file_exists($i18n_date_js_file))
  1737. {
  1738. $this->set_js($i18n_date_js_file);
  1739. }
  1740. }
  1741. }
  1742. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.datepicker.config.js');
  1743. if(!empty($value) && $value != '0000-00-00' && $value != '1970-01-01')
  1744. {
  1745. list($year,$month,$day) = explode('-',substr($value,0,10));
  1746. $date = date($this->php_date_format, mktime(0,0,0,$month,$day,$year));
  1747. }
  1748. else
  1749. {
  1750. $date = '';
  1751. }
  1752. $input = "<input id='field-{$field_info->name}' name='{$field_info->name}' type='text' value='$date' maxlength='10' class='datepicker-input' />
  1753. <a class='datepicker-input-clear' tabindex='-1'>".$this->l('form_button_clear')."</a> (".$this->ui_date_format.")";
  1754. return $input;
  1755. }
  1756. protected function get_dropdown_input($field_info,$value)
  1757. {
  1758. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1759. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1760. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1761. $select_title = str_replace('{field_display_as}',$field_info->display_as,$this->l('set_relation_title'));
  1762. $input = "<select id='field-{$field_info->name}' name='{$field_info->name}' class='chosen-select' data-placeholder='".$select_title."'>";
  1763. $options = array('' => '') + $field_info->extras;
  1764. foreach($options as $option_value => $option_label)
  1765. {
  1766. $selected = !empty($value) && $value == $option_value ? "selected='selected'" : '';
  1767. $input .= "<option value='$option_value' $selected >$option_label</option>";
  1768. }
  1769. $input .= "</select>";
  1770. return $input;
  1771. }
  1772. protected function get_enum_input($field_info,$value)
  1773. {
  1774. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1775. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1776. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1777. $select_title = str_replace('{field_display_as}',$field_info->display_as,$this->l('set_relation_title'));
  1778. $input = "<select id='field-{$field_info->name}' name='{$field_info->name}' class='chosen-select' data-placeholder='".$select_title."'>";
  1779. $options_array = $field_info->extras !== false && is_array($field_info->extras)? $field_info->extras : explode("','",substr($field_info->db_max_length,1,-1));
  1780. $options_array = array('' => '') + $options_array;
  1781. foreach($options_array as $option)
  1782. {
  1783. $selected = !empty($value) && $value == $option ? "selected='selected'" : '';
  1784. $input .= "<option value='$option' $selected >$option</option>";
  1785. }
  1786. $input .= "</select>";
  1787. return $input;
  1788. }
  1789. protected function get_readonly_input($field_info,$value)
  1790. {
  1791. return '<div id="field-'.$field_info->name.'" class="readonly_label">'.$value.'</div>';
  1792. }
  1793. protected function get_set_input($field_info,$value)
  1794. {
  1795. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1796. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1797. $this->set_js($this->default_javascript_path.'/jquery_plugins/ajax-chosen.js');
  1798. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1799. $options_array = $field_info->extras !== false && is_array($field_info->extras)? $field_info->extras : explode("','",substr($field_info->db_max_length,1,-1));
  1800. $selected_values = !empty($value) ? explode(",",$value) : array();
  1801. $select_title = str_replace('{field_display_as}',$field_info->display_as,$this->l('set_relation_title'));
  1802. $input = "<select id='field-{$field_info->name}' name='{$field_info->name}[]' multiple='multiple' size='8' class='chosen-multiple-select' data-placeholder='$select_title' style='width:510px;' >";
  1803. foreach($options_array as $option)
  1804. {
  1805. $selected = !empty($value) && in_array($option,$selected_values) ? "selected='selected'" : '';
  1806. $input .= "<option value='$option' $selected >$option</option>";
  1807. }
  1808. $input .= "</select>";
  1809. return $input;
  1810. }
  1811. protected function get_multiselect_input($field_info,$value)
  1812. {
  1813. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1814. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1815. $this->set_js($this->default_javascript_path.'/jquery_plugins/ajax-chosen.js');
  1816. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1817. $options_array = $field_info->extras;
  1818. $selected_values = !empty($value) ? explode(",",$value) : array();
  1819. $select_title = str_replace('{field_display_as}',$field_info->display_as,$this->l('set_relation_title'));
  1820. $input = "<select id='field-{$field_info->name}' name='{$field_info->name}[]' multiple='multiple' size='8' class='chosen-multiple-select' data-placeholder='$select_title' style='width:510px;' >";
  1821. foreach($options_array as $option_value => $option_label)
  1822. {
  1823. $selected = !empty($value) && in_array($option_value,$selected_values) ? "selected='selected'" : '';
  1824. $input .= "<option value='$option_value' $selected >$option_label</option>";
  1825. }
  1826. $input .= "</select>";
  1827. return $input;
  1828. }
  1829. protected function get_relation_input($field_info,$value)
  1830. {
  1831. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1832. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1833. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1834. $ajax_limitation = 10000;
  1835. $total_rows = $this->get_relation_total_rows($field_info->extras);
  1836. //Check if we will use ajax for our queries or just clien-side javascript
  1837. $using_ajax = $total_rows > $ajax_limitation ? true : false;
  1838. //We will not use it for now. It is not ready yet. Probably we will have this functionality at version 1.4
  1839. $using_ajax = false;
  1840. //If total rows are more than the limitation, use the ajax plugin
  1841. $ajax_or_not_class = $using_ajax ? 'chosen-select' : 'chosen-select';
  1842. $this->_inline_js("var ajax_relation_url = '".$this->getAjaxRelationUrl()."';\n");
  1843. $select_title = str_replace('{field_display_as}',$field_info->display_as,$this->l('set_relation_title'));
  1844. $input = "<select id='field-{$field_info->name}' name='{$field_info->name}' class='$ajax_or_not_class' data-placeholder='$select_title' style='width:300px'>";
  1845. $input .= "<option value=''></option>";
  1846. if(!$using_ajax)
  1847. {
  1848. $options_array = $this->get_relation_array($field_info->extras);
  1849. foreach($options_array as $option_value => $option)
  1850. {
  1851. $selected = !empty($value) && $value == $option_value ? "selected='selected'" : '';
  1852. $input .= "<option value='$option_value' $selected >$option</option>";
  1853. }
  1854. }
  1855. elseif(!empty($value) || (is_numeric($value) && $value == '0') ) //If it's ajax then we only need the selected items and not all the items
  1856. {
  1857. $selected_options_array = $this->get_relation_array($field_info->extras, $value);
  1858. foreach($selected_options_array as $option_value => $option)
  1859. {
  1860. $input .= "<option value='$option_value'selected='selected' >$option</option>";
  1861. }
  1862. }
  1863. $input .= "</select>";
  1864. return $input;
  1865. }
  1866. protected function get_relation_n_n_input($field_info_type, $selected_values)
  1867. {
  1868. $has_priority_field = !empty($field_info_type->extras->priority_field_relation_table) ? true : false;
  1869. $is_ie_7 = isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7') !== false) ? true : false;
  1870. if($has_priority_field || $is_ie_7)
  1871. {
  1872. $this->set_css($this->default_css_path.'/ui/simple/'.grocery_CRUD::JQUERY_UI_CSS);
  1873. $this->set_css($this->default_css_path.'/jquery_plugins/ui.multiselect.css');
  1874. $this->set_js($this->default_javascript_path.'/jquery_plugins/ui/'.grocery_CRUD::JQUERY_UI_JS);
  1875. $this->set_js($this->default_javascript_path.'/jquery_plugins/ui.multiselect.min.js');
  1876. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.multiselect.js');
  1877. if($this->language !== 'english')
  1878. {
  1879. include($this->default_config_path.'/language_alias.php');
  1880. if(array_key_exists($this->language, $language_alias))
  1881. {
  1882. $i18n_date_js_file = $this->default_javascript_path.'/jquery_plugins/ui/i18n/multiselect/ui-multiselect-'.$language_alias[$this->language].'.js';
  1883. if(file_exists($i18n_date_js_file))
  1884. {
  1885. $this->set_js($i18n_date_js_file);
  1886. }
  1887. }
  1888. }
  1889. }
  1890. else
  1891. {
  1892. $this->set_css($this->default_css_path.'/jquery_plugins/chosen/chosen.css');
  1893. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.chosen.min.js');
  1894. $this->set_js($this->default_javascript_path.'/jquery_plugins/ajax-chosen.js');
  1895. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.chosen.config.js');
  1896. }
  1897. $this->_inline_js("var ajax_relation_url = '".$this->getAjaxRelationUrl()."';\n");
  1898. $field_info = $this->relation_n_n[$field_info_type->name]; //As we use this function the relation_n_n exists, so don't need to check
  1899. $unselected_values = $this->get_relation_n_n_unselected_array($field_info, $selected_values);
  1900. if(empty($unselected_values) && empty($selected_values))
  1901. {
  1902. $input = "Please add {$field_info_type->display_as} first";
  1903. }
  1904. else
  1905. {
  1906. $css_class = $has_priority_field || $is_ie_7 ? 'multiselect': 'chosen-multiple-select';
  1907. $width_style = $has_priority_field || $is_ie_7 ? '' : 'width:510px;';
  1908. $select_title = str_replace('{field_display_as}',$field_info_type->display_as,$this->l('set_relation_title'));
  1909. $input = "<select id='field-{$field_info_type->name}' name='{$field_info_type->name}[]' multiple='multiple' size='8' class='$css_class' data-placeholder='$select_title' style='$width_style' >";
  1910. if(!empty($unselected_values))
  1911. foreach($unselected_values as $id => $name)
  1912. {
  1913. $input .= "<option value='$id'>$name</option>";
  1914. }
  1915. if(!empty($selected_values))
  1916. foreach($selected_values as $id => $name)
  1917. {
  1918. $input .= "<option value='$id' selected='selected'>$name</option>";
  1919. }
  1920. $input .= "</select>";
  1921. }
  1922. return $input;
  1923. }
  1924. protected function _convert_bytes_ui_to_bytes($bytes_ui)
  1925. {
  1926. $bytes_ui = str_replace(' ','',$bytes_ui);
  1927. if(strstr($bytes_ui,'MB'))
  1928. $bytes = (int)(str_replace('MB','',$bytes_ui))*1024*1024;
  1929. elseif(strstr($bytes_ui,'KB'))
  1930. $bytes = (int)(str_replace('KB','',$bytes_ui))*1024;
  1931. elseif(strstr($bytes_ui,'B'))
  1932. $bytes = (int)(str_replace('B','',$bytes_ui));
  1933. else
  1934. $bytes = (int)($bytes_ui);
  1935. return $bytes;
  1936. }
  1937. protected function get_upload_file_input($field_info, $value)
  1938. {
  1939. $this->set_css($this->default_css_path.'/ui/simple/'.grocery_CRUD::JQUERY_UI_CSS);
  1940. $this->set_css($this->default_css_path.'/jquery_plugins/file_upload/file-uploader.css');
  1941. $this->set_css($this->default_css_path.'/jquery_plugins/file_upload/jquery.fileupload-ui.css');
  1942. $this->set_js($this->default_javascript_path.'/jquery_plugins/ui/'.grocery_CRUD::JQUERY_UI_JS);
  1943. $this->set_js($this->default_javascript_path.'/jquery_plugins/tmpl.min.js');
  1944. $this->set_js($this->default_javascript_path.'/jquery_plugins/load-image.min.js');
  1945. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.iframe-transport.js');
  1946. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.fileupload.js');
  1947. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.fileupload.config.js');
  1948. //Fancybox
  1949. $this->set_css($this->default_css_path.'/jquery_plugins/fancybox/jquery.fancybox.css');
  1950. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.fancybox.pack.js');
  1951. $this->set_js($this->default_javascript_path.'/jquery_plugins/jquery.easing-1.3.pack.js');
  1952. $this->set_js($this->default_javascript_path.'/jquery_plugins/config/jquery.fancybox.config.js');
  1953. $unique = uniqid();
  1954. $allowed_files = $this->config->file_upload_allow_file_types;
  1955. $allowed_files_ui = '.'.str_replace('|',',.',$allowed_files);
  1956. $max_file_size_ui = $this->config->file_upload_max_file_size;
  1957. $max_file_size_bytes = $this->_convert_bytes_ui_to_bytes($max_file_size_ui);
  1958. $this->_inline_js('
  1959. var upload_info_'.$unique.' = {
  1960. accepted_file_types: /(\\.|\\/)('.$allowed_files.')$/i,
  1961. accepted_file_types_ui : "'.$allowed_files_ui.'",
  1962. max_file_size: '.$max_file_size_bytes.',
  1963. max_file_size_ui: "'.$max_file_size_ui.'"
  1964. };
  1965. var string_upload_file = "'.$this->l('form_upload_a_file').'";
  1966. var string_delete_file = "'.$this->l('string_delete_file').'";
  1967. var string_progress = "'.$this->l('string_progress').'";
  1968. var error_on_uploading = "'.$this->l('error_on_uploading').'";
  1969. var message_prompt_delete_file = "'.$this->l('message_prompt_delete_file').'";
  1970. var error_max_number_of_files = "'.$this->l('error_max_number_of_files').'";
  1971. var error_accept_file_types = "'.$this->l('error_accept_file_types').'";
  1972. var error_max_file_size = "'.str_replace("{max_file_size}",$max_file_size_ui,$this->l('error_max_file_size')).'";
  1973. var error_min_file_size = "'.$this->l('error_min_file_size').'";
  1974. var base_url = "'.base_url().'";
  1975. var upload_a_file_string = "'.$this->l('form_upload_a_file').'";
  1976. ');
  1977. $uploader_display_none = empty($value) ? "" : "display:none;";
  1978. $file_display_none = empty($value) ? "display:none;" : "";
  1979. $is_image = !empty($value) &&
  1980. ( substr($value,-4) == '.jpg'
  1981. || substr($value,-4) == '.png'
  1982. || substr($value,-5) == '.jpeg'
  1983. || substr($value,-4) == '.gif'
  1984. || substr($value,-5) == '.tiff')
  1985. ? true : false;
  1986. $image_class = $is_image ? 'image-thumbnail' : '';
  1987. $input = '<span class="fileinput-button qq-upload-button" id="upload-button-'.$unique.'" style="'.$uploader_display_none.'">
  1988. <span>'.$this->l('form_upload_a_file').'</span>
  1989. <input type="file" name="'.$this->_unique_field_name($field_info->name).'" class="gc-file-upload" rel="'.$this->getUploadUrl($field_info->name).'" id="'.$unique.'">
  1990. <input class="hidden-upload-input" type="hidden" name="'.$field_info->name.'" value="'.$value.'" rel="'.$this->_unique_field_name($field_info->name).'" />
  1991. </span>';
  1992. $this->set_css($this->default_css_path.'/jquery_plugins/file_upload/fileuploader.css');
  1993. $file_url = base_url().$field_info->extras->upload_path.'/'.$value;
  1994. $input .= "<div id='uploader_$unique' rel='$unique' class='grocery-crud-uploader' style='$uploader_display_none'></div>";
  1995. $input .= "<div id='success_$unique' class='upload-success-url' style='$file_display_none padding-top:7px;'>";
  1996. $input .= "<a href='".$file_url."' id='file_$unique' class='open-file";
  1997. $input .= $is_image ? " $image_class'><img src='".$file_url."' height='50px'>" : "' target='_blank'>$value";
  1998. $input .= "</a> ";
  1999. $input .= "<a href='javascript:void(0)' id='delete_$unique' class='delete-anchor'>".$this->l('form_upload_delete')."</a> ";
  2000. $input .= "</div><div style='clear:both'></div>";
  2001. $input .= "<div id='loading-$unique' style='display:none'><span id='upload-state-message-$unique'></span> <span class='qq-upload-spinner'></span> <span id='progress-$unique'></span></div>";
  2002. $input .= "<div style='display:none'><a href='".$this->getUploadUrl($field_info->name)."' id='url_$unique'></a></div>";
  2003. $input .= "<div style='display:none'><a href='".$this->getFileDeleteUrl($field_info->name)."' id='delete_url_$unique' rel='$value' ></a></div>";
  2004. return $input;
  2005. }
  2006. protected function get_add_hidden_fields()
  2007. {
  2008. return $this->add_hidden_fields;
  2009. }
  2010. protected function get_edit_hidden_fields()
  2011. {
  2012. return $this->edit_hidden_fields;
  2013. }
  2014. protected function get_add_input_fields($field_values = null)
  2015. {
  2016. $fields = $this->get_add_fields();
  2017. $types = $this->get_field_types();
  2018. $input_fields = array();
  2019. foreach($fields as $field_num => $field)
  2020. {
  2021. $field_info = $types[$field->field_name];
  2022. $field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
  2023. if(!isset($this->callback_add_field[$field->field_name]))
  2024. {
  2025. $field_input = $this->get_field_input($field_info, $field_value);
  2026. }
  2027. else
  2028. {
  2029. $field_input = $field_info;
  2030. $field_input->input = call_user_func($this->callback_add_field[$field->field_name], $field_value, null, $field_info);
  2031. }
  2032. switch ($field_info->crud_type) {
  2033. case 'invisible':
  2034. unset($this->add_fields[$field_num]);
  2035. unset($fields[$field_num]);
  2036. continue;
  2037. break;
  2038. case 'hidden':
  2039. $this->add_hidden_fields[] = $field_input;
  2040. unset($this->add_fields[$field_num]);
  2041. unset($fields[$field_num]);
  2042. continue;
  2043. break;
  2044. }
  2045. $input_fields[$field->field_name] = $field_input;
  2046. }
  2047. return $input_fields;
  2048. }
  2049. protected function get_edit_input_fields($field_values = null)
  2050. {
  2051. $fields = $this->get_edit_fields();
  2052. $types = $this->get_field_types();
  2053. $input_fields = array();
  2054. foreach($fields as $field_num => $field)
  2055. {
  2056. $field_info = $types[$field->field_name];
  2057. $field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
  2058. if(!isset($this->callback_edit_field[$field->field_name]))
  2059. {
  2060. $field_input = $this->get_field_input($field_info, $field_value);
  2061. }
  2062. else
  2063. {
  2064. $primary_key = $this->getStateInfo()->primary_key;
  2065. $field_input = $field_info;
  2066. $field_input->input = call_user_func($this->callback_edit_field[$field->field_name], $field_value, $primary_key, $field_info, $field_values);
  2067. }
  2068. switch ($field_info->crud_type) {
  2069. case 'invisible':
  2070. unset($this->edit_fields[$field_num]);
  2071. unset($fields[$field_num]);
  2072. continue;
  2073. break;
  2074. case 'hidden':
  2075. $this->edit_hidden_fields[] = $field_input;
  2076. unset($this->edit_fields[$field_num]);
  2077. unset($fields[$field_num]);
  2078. continue;
  2079. break;
  2080. }
  2081. $input_fields[$field->field_name] = $field_input;
  2082. }
  2083. return $input_fields;
  2084. }
  2085. protected function setThemeBasics()
  2086. {
  2087. $this->theme_path = $this->default_theme_path;
  2088. if(substr($this->theme_path,-1) != '/')
  2089. $this->theme_path = $this->theme_path.'/';
  2090. include($this->theme_path.$this->theme.'/config.php');
  2091. $this->theme_config = $config;
  2092. }
  2093. public function set_theme($theme = null)
  2094. {
  2095. $this->theme = $theme;
  2096. }
  2097. protected function _theme_view($view, $vars = array(), $return = FALSE)
  2098. {
  2099. $vars = (is_object($vars)) ? get_object_vars($vars) : $vars;
  2100. $file_exists = FALSE;
  2101. $ext = pathinfo($view, PATHINFO_EXTENSION);
  2102. $file = ($ext == '') ? $view.'.php' : $view;
  2103. $view_file = $this->theme_path.$this->theme.'/views/';
  2104. if (file_exists($view_file.$file))
  2105. {
  2106. $path = $view_file.$file;
  2107. $file_exists = TRUE;
  2108. }
  2109. if ( ! $file_exists)
  2110. {
  2111. throw new Exception('Unable to load the requested file: '.$file, 16);
  2112. }
  2113. extract($vars);
  2114. #region buffering...
  2115. ob_start();
  2116. include($path);
  2117. $buffer = ob_get_contents();
  2118. @ob_end_clean();
  2119. #endregion
  2120. if ($return === TRUE)
  2121. {
  2122. return $buffer;
  2123. }
  2124. $this->views_as_string .= $buffer;
  2125. }
  2126. protected function _inline_js($inline_js = '')
  2127. {
  2128. $this->views_as_string .= "<script type=\"text/javascript\">\n{$inline_js}\n</script>\n";
  2129. }
  2130. protected function _add_js_vars($js_vars = array())
  2131. {
  2132. $javascript_as_string = "<script type=\"text/javascript\">\n";
  2133. foreach ($js_vars as $js_var => $js_value) {
  2134. $javascript_as_string .= "\tvar $js_var = '$js_value';\n";
  2135. }
  2136. $javascript_as_string .= "\n</script>\n";
  2137. $this->views_as_string .= $javascript_as_string;
  2138. }
  2139. protected function get_views_as_string()
  2140. {
  2141. if(!empty($this->views_as_string))
  2142. return $this->views_as_string;
  2143. else
  2144. return null;
  2145. }
  2146. }
  2147. /**
  2148. * PHP grocery CRUD
  2149. *
  2150. * LICENSE
  2151. *
  2152. * Grocery CRUD is released with dual licensing, using the GPL v3 (license-gpl3.txt) and the MIT license (license-mit.txt).
  2153. * You don't have to do anything special to choose one license or the other and you don't have to notify anyone which license you are using.
  2154. * Please see the corresponding license file for details of these licenses.
  2155. * You are free to use, modify and distribute this software, but all copyright information must remain.
  2156. *
  2157. * @package grocery CRUD
  2158. * @copyright Copyright (c) 2010 through 2012, John Skoumbourdis
  2159. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  2160. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  2161. */
  2162. // ------------------------------------------------------------------------
  2163. /**
  2164. * PHP grocery States
  2165. *
  2166. * States of grocery CRUD
  2167. *
  2168. * @package grocery CRUD
  2169. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  2170. * @version 1.3
  2171. */
  2172. class grocery_CRUD_States extends grocery_CRUD_Layout
  2173. {
  2174. protected $states = array(
  2175. 0 => 'unknown',
  2176. 1 => 'list',
  2177. 2 => 'add',
  2178. 3 => 'edit',
  2179. 4 => 'delete',
  2180. 5 => 'insert',
  2181. 6 => 'update',
  2182. 7 => 'ajax_list',
  2183. 8 => 'ajax_list_info',
  2184. 9 => 'insert_validation',
  2185. 10 => 'update_validation',
  2186. 11 => 'upload_file',
  2187. 12 => 'delete_file',
  2188. 13 => 'ajax_relation',
  2189. 14 => 'ajax_relation_n_n',
  2190. 15 => 'success',
  2191. 16 => 'export',
  2192. 17 => 'print'
  2193. );
  2194. protected function getStateCode()
  2195. {
  2196. $state_string = $this->get_state_info_from_url()->operation;
  2197. if( $state_string != 'unknown' && in_array( $state_string, $this->states ) )
  2198. $state_code = array_search($state_string, $this->states);
  2199. else
  2200. $state_code = 0;
  2201. return $state_code;
  2202. }
  2203. protected function state_url($url = '')
  2204. {
  2205. $ci = &get_instance();
  2206. $segment_object = $this->get_state_info_from_url();
  2207. $method_name = $this->get_method_name();
  2208. $segment_position = $segment_object->segment_position;
  2209. $state_url_array = array();
  2210. if( sizeof($ci->uri->segments) > 0 ) {
  2211. foreach($ci->uri->segments as $num => $value)
  2212. {
  2213. $state_url_array[$num] = $value;
  2214. if($num == ($segment_position - 1))
  2215. break;
  2216. }
  2217. if( $method_name == 'index' && !in_array( 'index', $state_url_array ) ) //there is a scenario that you don't have the index to your url
  2218. $state_url_array[$num+1] = 'index';
  2219. }
  2220. $state_url = implode('/',$state_url_array).'/'.$url;
  2221. return site_url($state_url);
  2222. }
  2223. protected function get_state_info_from_url()
  2224. {
  2225. $ci = &get_instance();
  2226. $segment_position = count($ci->uri->segments) + 1;
  2227. $operation = 'list';
  2228. $segements = $ci->uri->segments;
  2229. foreach($segements as $num => $value)
  2230. {
  2231. if($value != 'unknown' && in_array($value, $this->states))
  2232. {
  2233. $segment_position = (int)$num;
  2234. $operation = $value; //I don't have a "break" here because I want to ensure that is the LAST segment with name that is in the array.
  2235. }
  2236. }
  2237. $function_name = $this->get_method_name();
  2238. if($function_name == 'index' && !in_array('index',$ci->uri->segments))
  2239. $segment_position++;
  2240. $first_parameter = isset($segements[$segment_position+1]) ? $segements[$segment_position+1] : null;
  2241. $second_parameter = isset($segements[$segment_position+2]) ? $segements[$segment_position+2] : null;
  2242. return (object)array('segment_position' => $segment_position, 'operation' => $operation, 'first_parameter' => $first_parameter, 'second_parameter' => $second_parameter);
  2243. }
  2244. protected function get_method_hash()
  2245. {
  2246. $ci = &get_instance();
  2247. $state_info = $this->get_state_info_from_url();
  2248. $extra_values = $ci->uri->segment($state_info->segment_position - 1) != $this->get_method_name() ? $ci->uri->segment($state_info->segment_position - 1) : '';
  2249. return md5($this->get_controller_name().$this->get_method_name().$extra_values);
  2250. }
  2251. protected function get_method_name()
  2252. {
  2253. $ci = &get_instance();
  2254. return $ci->router->method;
  2255. }
  2256. protected function get_controller_name()
  2257. {
  2258. $ci = &get_instance();
  2259. return $ci->router->class;
  2260. }
  2261. public function getState()
  2262. {
  2263. return $this->states[$this->getStateCode()];
  2264. }
  2265. protected function getListUrl()
  2266. {
  2267. return $this->state_url('');
  2268. }
  2269. protected function getAjaxListUrl()
  2270. {
  2271. return $this->state_url('ajax_list');
  2272. }
  2273. protected function getExportToExcelUrl()
  2274. {
  2275. return $this->state_url('export');
  2276. }
  2277. protected function getPrintUrl()
  2278. {
  2279. return $this->state_url('print');
  2280. }
  2281. protected function getAjaxListInfoUrl()
  2282. {
  2283. return $this->state_url('ajax_list_info');
  2284. }
  2285. protected function getAddUrl()
  2286. {
  2287. return $this->state_url('add');
  2288. }
  2289. protected function getInsertUrl()
  2290. {
  2291. return $this->state_url('insert');
  2292. }
  2293. protected function getValidationInsertUrl()
  2294. {
  2295. return $this->state_url('insert_validation');
  2296. }
  2297. protected function getValidationUpdateUrl($primary_key = null)
  2298. {
  2299. if($primary_key === null)
  2300. return $this->state_url('update_validation');
  2301. else
  2302. return $this->state_url('update_validation/'.$primary_key);
  2303. }
  2304. protected function getEditUrl($primary_key = null)
  2305. {
  2306. if($primary_key === null)
  2307. return $this->state_url('edit');
  2308. else
  2309. return $this->state_url('edit/'.$primary_key);
  2310. }
  2311. protected function getUpdateUrl($state_info)
  2312. {
  2313. return $this->state_url('update/'.$state_info->primary_key);
  2314. }
  2315. protected function getDeleteUrl($state_info = null)
  2316. {
  2317. if(empty($state_info))
  2318. return $this->state_url('delete');
  2319. else
  2320. return $this->state_url('delete/'.$state_info->primary_key);
  2321. }
  2322. protected function getListSuccessUrl($primary_key = null)
  2323. {
  2324. if(empty($primary_key))
  2325. return $this->state_url('success');
  2326. else
  2327. return $this->state_url('success/'.$primary_key);
  2328. }
  2329. protected function getUploadUrl($field_name)
  2330. {
  2331. return $this->state_url('upload_file/'.$field_name);
  2332. }
  2333. protected function getFileDeleteUrl($field_name)
  2334. {
  2335. return $this->state_url('delete_file/'.$field_name);
  2336. }
  2337. protected function getAjaxRelationUrl()
  2338. {
  2339. return $this->state_url('ajax_relation');
  2340. }
  2341. protected function getAjaxRelationManytoManyUrl()
  2342. {
  2343. return $this->state_url('ajax_relation_n_n');
  2344. }
  2345. public function getStateInfo()
  2346. {
  2347. $state_code = $this->getStateCode();
  2348. $segment_object = $this->get_state_info_from_url();
  2349. $first_parameter = $segment_object->first_parameter;
  2350. $second_parameter = $segment_object->second_parameter;
  2351. $state_info = (object)array();
  2352. switch ($state_code) {
  2353. case 1:
  2354. case 2:
  2355. break;
  2356. case 3:
  2357. if($first_parameter !== null)
  2358. {
  2359. $state_info = (object)array('primary_key' => $first_parameter);
  2360. }
  2361. else
  2362. {
  2363. throw new Exception('On the state "edit" the Primary key cannot be null', 6);
  2364. die();
  2365. }
  2366. break;
  2367. case 4:
  2368. if($first_parameter !== null)
  2369. {
  2370. $state_info = (object)array('primary_key' => $first_parameter);
  2371. }
  2372. else
  2373. {
  2374. throw new Exception('On the state "delete" the Primary key cannot be null',7);
  2375. die();
  2376. }
  2377. break;
  2378. case 5:
  2379. if(!empty($_POST))
  2380. {
  2381. $state_info = (object)array('unwrapped_data' => $_POST);
  2382. }
  2383. else
  2384. {
  2385. throw new Exception('On the state "insert" you must have post data',8);
  2386. die();
  2387. }
  2388. break;
  2389. case 6:
  2390. if(!empty($_POST) && $first_parameter !== null)
  2391. {
  2392. $state_info = (object)array('primary_key' => $first_parameter,'unwrapped_data' => $_POST);
  2393. }
  2394. elseif(empty($_POST))
  2395. {
  2396. throw new Exception('On the state "update" you must have post data',9);
  2397. die();
  2398. }
  2399. else
  2400. {
  2401. throw new Exception('On the state "update" the Primary key cannot be null',10);
  2402. die();
  2403. }
  2404. break;
  2405. case 7:
  2406. case 8:
  2407. case 16: //export to excel
  2408. case 17: //print
  2409. $state_info = (object)array();
  2410. if(!empty($_POST['per_page']))
  2411. {
  2412. $state_info->per_page = is_numeric($_POST['per_page']) ? $_POST['per_page'] : null;
  2413. }
  2414. if(!empty($_POST['page']))
  2415. {
  2416. $state_info->page = is_numeric($_POST['page']) ? $_POST['page'] : null;
  2417. }
  2418. //If we request an export or a print we don't care about what page we are
  2419. if($state_code === 16 || $state_code === 17)
  2420. {
  2421. $state_info->page = 1;
  2422. $state_info->per_page = 1000000; //a big number
  2423. }
  2424. if(!empty($_POST['order_by'][0]))
  2425. {
  2426. $state_info->order_by = $_POST['order_by'];
  2427. }
  2428. if(!empty($_POST['search_text']))
  2429. {
  2430. if(empty($_POST['search_field']))
  2431. {
  2432. $search_text = strip_tags($_POST['search_field']);
  2433. $state_info->search = (object)array( 'field' => null , 'text' => $_POST['search_text'] );
  2434. }
  2435. else
  2436. {
  2437. $state_info->search = (object)array( 'field' => strip_tags($_POST['search_field']) , 'text' => $_POST['search_text'] );
  2438. }
  2439. }
  2440. break;
  2441. case 9:
  2442. case 10:
  2443. break;
  2444. case 11:
  2445. $state_info->field_name = $first_parameter;
  2446. break;
  2447. case 12:
  2448. $state_info->field_name = $first_parameter;
  2449. $state_info->file_name = $second_parameter;
  2450. break;
  2451. case 13:
  2452. $state_info->field_name = $_POST['field_name'];
  2453. $state_info->search = $_POST['term'];
  2454. break;
  2455. case 14:
  2456. $state_info->field_name = $_POST['field_name'];
  2457. $state_info->search = $_POST['term'];
  2458. break;
  2459. case 15:
  2460. $state_info = (object)array(
  2461. 'primary_key' => $first_parameter,
  2462. 'success_message' => true
  2463. );
  2464. break;
  2465. }
  2466. return $state_info;
  2467. }
  2468. }
  2469. /**
  2470. * PHP grocery CRUD
  2471. *
  2472. * LICENSE
  2473. *
  2474. * Grocery CRUD is released with dual licensing, using the GPL v3 (license-gpl3.txt) and the MIT license (license-mit.txt).
  2475. * You don't have to do anything special to choose one license or the other and you don't have to notify anyone which license you are using.
  2476. * Please see the corresponding license file for details of these licenses.
  2477. * You are free to use, modify and distribute this software, but all copyright information must remain.
  2478. *
  2479. * @package grocery CRUD
  2480. * @copyright Copyright (c) 2010 through 2012, John Skoumbourdis
  2481. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  2482. * @version 1.3.3
  2483. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  2484. */
  2485. // ------------------------------------------------------------------------
  2486. /**
  2487. * PHP grocery CRUD
  2488. *
  2489. * Creates a full functional CRUD with few lines of code.
  2490. *
  2491. * @package grocery CRUD
  2492. * @author John Skoumbourdis <scoumbourdisj@gmail.com>
  2493. * @license https://github.com/scoumbourdis/grocery-crud/blob/master/license-grocery-crud.txt
  2494. * @link http://www.grocerycrud.com/documentation
  2495. */
  2496. class grocery_CRUD extends grocery_CRUD_States
  2497. {
  2498. /**
  2499. * Grocery CRUD version
  2500. *
  2501. * @var string
  2502. */
  2503. const VERSION = "1.3.3";
  2504. const JQUERY = "jquery-1.8.2.min.js";
  2505. const JQUERY_UI_JS = "jquery-ui-1.9.0.custom.min.js";
  2506. const JQUERY_UI_CSS = "jquery-ui-1.9.0.custom.min.css";
  2507. private $state_code = null;
  2508. private $state_info = null;
  2509. private $basic_db_table_checked = false;
  2510. private $columns = null;
  2511. private $columns_checked = false;
  2512. private $add_fields_checked = false;
  2513. private $edit_fields_checked = false;
  2514. protected $default_theme = 'flexigrid';
  2515. protected $language = null;
  2516. protected $lang_strings = array();
  2517. protected $php_date_format = null;
  2518. protected $js_date_format = null;
  2519. protected $ui_date_format = null;
  2520. protected $character_limiter = null;
  2521. protected $config = null;
  2522. protected $add_fields = null;
  2523. protected $edit_fields = null;
  2524. protected $add_hidden_fields = array();
  2525. protected $edit_hidden_fields = array();
  2526. protected $field_types = null;
  2527. protected $basic_db_table = null;
  2528. protected $theme_config = array();
  2529. protected $subject = null;
  2530. protected $subject_plural = null;
  2531. protected $display_as = array();
  2532. protected $order_by = null;
  2533. protected $where = array();
  2534. protected $like = array();
  2535. protected $having = array();
  2536. protected $or_having = array();
  2537. protected $limit = null;
  2538. protected $required_fields = array();
  2539. protected $validation_rules = array();
  2540. protected $relation = array();
  2541. protected $relation_n_n = array();
  2542. protected $upload_fields = array();
  2543. protected $actions = array();
  2544. protected $form_validation = null;
  2545. protected $change_field_type = null;
  2546. protected $primary_keys = array();
  2547. /* The unsetters */
  2548. protected $unset_texteditor = array();
  2549. protected $unset_add = false;
  2550. protected $unset_edit = false;
  2551. protected $unset_delete = false;
  2552. protected $unset_jquery = false;
  2553. protected $unset_jquery_ui = false;
  2554. protected $unset_list = false;
  2555. protected $unset_export = false;
  2556. protected $unset_print = false;
  2557. protected $unset_back_to_list = false;
  2558. protected $unset_columns = null;
  2559. protected $unset_add_fields = null;
  2560. protected $unset_edit_fields = null;
  2561. /* Callbacks */
  2562. protected $callback_before_insert = null;
  2563. protected $callback_after_insert = null;
  2564. protected $callback_insert = null;
  2565. protected $callback_before_update = null;
  2566. protected $callback_after_update = null;
  2567. protected $callback_update = null;
  2568. protected $callback_before_delete = null;
  2569. protected $callback_after_delete = null;
  2570. protected $callback_delete = null;
  2571. protected $callback_column = array();
  2572. protected $callback_add_field = array();
  2573. protected $callback_edit_field = array();
  2574. protected $callback_upload = null;
  2575. protected $callback_before_upload = null;
  2576. protected $callback_after_upload = null;
  2577. protected $default_javascript_path = null; //autogenerate, please do not modify
  2578. protected $default_css_path = null; //autogenerate, please do not modify
  2579. protected $default_texteditor_path = null; //autogenerate, please do not modify
  2580. protected $default_theme_path = null; //autogenerate, please do not modify
  2581. protected $default_language_path = 'assets/grocery_crud/languages';
  2582. protected $default_config_path = 'assets/grocery_crud/config';
  2583. protected $default_assets_path = 'assets/grocery_crud';
  2584. /**
  2585. *
  2586. * Constructor
  2587. *
  2588. * @access public
  2589. */
  2590. public function __construct()
  2591. {
  2592. }
  2593. /**
  2594. * The displayed columns that user see
  2595. *
  2596. * @access public
  2597. * @param string
  2598. * @param array
  2599. * @return void
  2600. */
  2601. public function columns()
  2602. {
  2603. $args = func_get_args();
  2604. if(isset($args[0]) && is_array($args[0]))
  2605. {
  2606. $args = $args[0];
  2607. }
  2608. $this->columns = $args;
  2609. return $this;
  2610. }
  2611. /**
  2612. * Set Validation Rules
  2613. *
  2614. * Important note: If the $field is an array then no automated crud fields will take apart
  2615. *
  2616. * @access public
  2617. * @param mixed
  2618. * @param string
  2619. * @return void
  2620. */
  2621. function set_rules($field, $label = '', $rules = '')
  2622. {
  2623. if(is_string($field))
  2624. {
  2625. $this->validation_rules[$field] = array('field' => $field, 'label' => $label, 'rules' => $rules);
  2626. }elseif(is_array($field))
  2627. {
  2628. foreach($field as $num_field => $field_array)
  2629. {
  2630. $this->validation_rules[$field_array['field']] = $field_array;
  2631. }
  2632. }
  2633. return $this;
  2634. }
  2635. /**
  2636. *
  2637. * Changes the default field type
  2638. * @param string $field
  2639. * @param string $type
  2640. * @param array|string $extras
  2641. */
  2642. public function change_field_type($field , $type, $extras = null)
  2643. {
  2644. $field_type = (object)array('type' => $type);
  2645. $field_type->extras = $extras;
  2646. $this->change_field_type[$field] = $field_type;
  2647. return $this;
  2648. }
  2649. /**
  2650. *
  2651. * Just an alias to the change_field_type method
  2652. * @param string $field
  2653. * @param string $type
  2654. * @param array|string $extras
  2655. */
  2656. public function field_type($field , $type, $extras = null)
  2657. {
  2658. return $this->change_field_type($field , $type, $extras);
  2659. }
  2660. /**
  2661. * Change the default primary key for a specific table.
  2662. * If the $table_name is NULL then the primary key is for the default table name that we added at the set_table method
  2663. *
  2664. * @param string $primary_key_field
  2665. * @param string $table_name
  2666. */
  2667. public function set_primary_key($primary_key_field, $table_name = null)
  2668. {
  2669. $this->primary_keys[] = array('field_name' => $primary_key_field, 'table_name' => $table_name);
  2670. return $this;
  2671. }
  2672. /**
  2673. * Unsets the texteditor of the selected fields
  2674. *
  2675. * @access public
  2676. * @param string
  2677. * @param array
  2678. * @return void
  2679. */
  2680. public function unset_texteditor()
  2681. {
  2682. $args = func_get_args();
  2683. if(isset($args[0]) && is_array($args[0]))
  2684. {
  2685. $args = $args[0];
  2686. }
  2687. foreach($args as $arg)
  2688. {
  2689. $this->unset_texteditor[] = $arg;
  2690. }
  2691. return $this;
  2692. }
  2693. /**
  2694. * Unsets just the jquery library from the js. This function can be used if there is already a jquery included
  2695. * in the main template. This will avoid all jquery conflicts.
  2696. *
  2697. * @return void
  2698. */
  2699. public function unset_jquery()
  2700. {
  2701. $this->unset_jquery = true;
  2702. return $this;
  2703. }
  2704. /**
  2705. * Unsets the jquery UI Javascript and CSS. This function is really useful
  2706. * when the jquery UI JavaScript and CSS are already included in the main template.
  2707. * This will avoid all jquery UI conflicts.
  2708. *
  2709. * @return void
  2710. */
  2711. public function unset_jquery_ui()
  2712. {
  2713. $this->unset_jquery_ui = true;
  2714. return $this;
  2715. }
  2716. /**
  2717. * Unsets the add operation from the list
  2718. *
  2719. * @return void
  2720. */
  2721. public function unset_add()
  2722. {
  2723. $this->unset_add = true;
  2724. return $this;
  2725. }
  2726. /**
  2727. * Unsets the edit operation from the list
  2728. *
  2729. * @return void
  2730. */
  2731. public function unset_edit()
  2732. {
  2733. $this->unset_edit = true;
  2734. return $this;
  2735. }
  2736. /**
  2737. * Unsets the delete operation from the list
  2738. *
  2739. * @return void
  2740. */
  2741. public function unset_delete()
  2742. {
  2743. $this->unset_delete = true;
  2744. return $this;
  2745. }
  2746. /**
  2747. * Unsets the export button and functionality from the list
  2748. *
  2749. * @return void
  2750. */
  2751. public function unset_export()
  2752. {
  2753. $this->unset_export = true;
  2754. return $this;
  2755. }
  2756. /**
  2757. * Unsets the print button and functionality from the list
  2758. *
  2759. * @return void
  2760. */
  2761. public function unset_print()
  2762. {
  2763. $this->unset_print = true;
  2764. return $this;
  2765. }
  2766. /**
  2767. * Unsets all the operations from the list
  2768. *
  2769. * @return void
  2770. */
  2771. public function unset_operations()
  2772. {
  2773. $this->unset_add = true;
  2774. $this->unset_edit = true;
  2775. $this->unset_delete = true;
  2776. $this->unset_export = true;
  2777. $this->unset_print = true;
  2778. return $this;
  2779. }
  2780. /**
  2781. * Unsets a column from the list
  2782. *
  2783. * @return void.
  2784. */
  2785. public function unset_columns()
  2786. {
  2787. $args = func_get_args();
  2788. if(isset($args[0]) && is_array($args[0]))
  2789. {
  2790. $args = $args[0];
  2791. }
  2792. $this->unset_columns = $args;
  2793. return $this;
  2794. }
  2795. public function unset_list()
  2796. {
  2797. $this->unset_list = true;
  2798. return $this;
  2799. }
  2800. public function unset_fields()
  2801. {
  2802. $args = func_get_args();
  2803. if(isset($args[0]) && is_array($args[0]))
  2804. {
  2805. $args = $args[0];
  2806. }
  2807. $this->unset_add_fields = $args;
  2808. $this->unset_edit_fields = $args;
  2809. return $this;
  2810. }
  2811. public function unset_add_fields()
  2812. {
  2813. $args = func_get_args();
  2814. if(isset($args[0]) && is_array($args[0]))
  2815. {
  2816. $args = $args[0];
  2817. }
  2818. $this->unset_add_fields = $args;
  2819. return $this;
  2820. }
  2821. public function unset_edit_fields()
  2822. {
  2823. $args = func_get_args();
  2824. if(isset($args[0]) && is_array($args[0]))
  2825. {
  2826. $args = $args[0];
  2827. }
  2828. $this->unset_edit_fields = $args;
  2829. return $this;
  2830. }
  2831. /**
  2832. * Unsets everything that has to do with buttons or links with go back to list message
  2833. * @access public
  2834. * @return void
  2835. */
  2836. public function unset_back_to_list()
  2837. {
  2838. $this->unset_back_to_list = true;
  2839. return $this;
  2840. }
  2841. /**
  2842. *
  2843. * The fields that user will see on add/edit
  2844. *
  2845. * @access public
  2846. * @param string
  2847. * @param array
  2848. * @return void
  2849. */
  2850. public function fields()
  2851. {
  2852. $args = func_get_args();
  2853. if(isset($args[0]) && is_array($args[0]))
  2854. {
  2855. $args = $args[0];
  2856. }
  2857. $this->add_fields = $args;
  2858. $this->edit_fields = $args;
  2859. return $this;
  2860. }
  2861. /**
  2862. *
  2863. * The fields that user can see . It is only for the add form
  2864. */
  2865. public function add_fields()
  2866. {
  2867. $args = func_get_args();
  2868. if(isset($args[0]) && is_array($args[0]))
  2869. {
  2870. $args = $args[0];
  2871. }
  2872. $this->add_fields = $args;
  2873. return $this;
  2874. }
  2875. /**
  2876. *
  2877. * The fields that user can see . It is only for the edit form
  2878. */
  2879. public function edit_fields()
  2880. {
  2881. $args = func_get_args();
  2882. if(isset($args[0]) && is_array($args[0]))
  2883. {
  2884. $args = $args[0];
  2885. }
  2886. $this->edit_fields = $args;
  2887. return $this;
  2888. }
  2889. /**
  2890. *
  2891. * Changes the displaying label of the field
  2892. * @param $field_name
  2893. * @param $display_as
  2894. * @return void
  2895. */
  2896. public function display_as($field_name, $display_as = null)
  2897. {
  2898. if(is_array($field_name))
  2899. {
  2900. foreach($field_name as $field => $display_as)
  2901. {
  2902. $this->display_as[$field] = $display_as;
  2903. }
  2904. }
  2905. elseif($display_as !== null)
  2906. {
  2907. $this->display_as[$field_name] = $display_as;
  2908. }
  2909. return $this;
  2910. }
  2911. /**
  2912. *
  2913. * Load the language strings array from the language file
  2914. */
  2915. protected function _load_language()
  2916. {
  2917. if($this->language === null)
  2918. {
  2919. $this->language = strtolower($this->config->default_language);
  2920. }
  2921. include($this->default_language_path.'/'.$this->language.'.php');
  2922. foreach($lang as $handle => $lang_string)
  2923. if(!isset($this->lang_strings[$handle]))
  2924. $this->lang_strings[$handle] = $lang_string;
  2925. $this->default_true_false_text = array( $this->l('form_inactive') , $this->l('form_active'));
  2926. $this->subject = $this->subject === null ? $this->l('list_record') : $this->subject;
  2927. }
  2928. protected function _load_date_format()
  2929. {
  2930. list($php_day, $php_month, $php_year) = array('d','m','Y');
  2931. list($js_day, $js_month, $js_year) = array('dd','mm','yy');
  2932. list($ui_day, $ui_month, $ui_year) = array('dd','mm','yyyy');
  2933. //@todo ui_day, ui_month, ui_year has to be lang strings
  2934. $date_format = $this->config->date_format;
  2935. switch ($date_format) {
  2936. case 'uk-date':
  2937. $this->php_date_format = "$php_day/$php_month/$php_year";
  2938. $this->js_date_format = "$js_day/$js_month/$js_year";
  2939. $this->ui_date_format = "$ui_day/$ui_month/$ui_year";
  2940. break;
  2941. case 'us-date':
  2942. $this->php_date_format = "$php_month/$php_day/$php_year";
  2943. $this->js_date_format = "$js_month/$js_day/$js_year";
  2944. $this->ui_date_format = "$ui_month/$ui_day/$ui_year";
  2945. break;
  2946. case 'sql-date':
  2947. default:
  2948. $this->php_date_format = "$php_year-$php_month-$php_day";
  2949. $this->js_date_format = "$js_year-$js_month-$js_day";
  2950. $this->ui_date_format = "$ui_year-$ui_month-$ui_day";
  2951. break;
  2952. }
  2953. }
  2954. /**
  2955. *
  2956. * Set a language string directly
  2957. * @param string $handle
  2958. * @param string $string
  2959. */
  2960. public function set_lang_string($handle, $lang_string){
  2961. $this->lang_strings[$handle] = $lang_string;
  2962. return $this;
  2963. }
  2964. /**
  2965. *
  2966. * Just an alias to get_lang_string method
  2967. * @param string $handle
  2968. */
  2969. public function l($handle)
  2970. {
  2971. return $this->get_lang_string($handle);
  2972. }
  2973. /**
  2974. *
  2975. * Get the language string of the inserted string handle
  2976. * @param string $handle
  2977. */
  2978. public function get_lang_string($handle)
  2979. {
  2980. return $this->lang_strings[$handle];
  2981. }
  2982. /**
  2983. *
  2984. * Simply set the language
  2985. * @example english
  2986. * @param string $language
  2987. */
  2988. public function set_language($language)
  2989. {
  2990. $this->language = $language;
  2991. return $this;
  2992. }
  2993. /**
  2994. *
  2995. * Enter description here ...
  2996. */
  2997. protected function get_columns()
  2998. {
  2999. if($this->columns_checked === false)
  3000. {
  3001. $field_types = $this->get_field_types();
  3002. if(empty($this->columns))
  3003. {
  3004. $this->columns = array();
  3005. foreach($field_types as $field)
  3006. {
  3007. if( !isset($field->db_extra) || $field->db_extra != 'auto_increment' )
  3008. $this->columns[] = $field->name;
  3009. }
  3010. }
  3011. foreach($this->columns as $col_num => $column)
  3012. {
  3013. if(isset($this->relation[$column]))
  3014. {
  3015. $new_column = $this->_unique_field_name($this->relation[$column][0]);
  3016. $this->columns[$col_num] = $new_column;
  3017. if(isset($this->display_as[$column]))
  3018. {
  3019. $display_as = $this->display_as[$column];
  3020. unset($this->display_as[$column]);
  3021. $this->display_as[$new_column] = $display_as;
  3022. }
  3023. else
  3024. {
  3025. $this->display_as[$new_column] = ucfirst(str_replace('_',' ',$column));
  3026. }
  3027. $column = $new_column;
  3028. $this->columns[$col_num] = $new_column;
  3029. }
  3030. else
  3031. {
  3032. if(!empty($this->relation))
  3033. {
  3034. $table_name = $this->get_table();
  3035. foreach($this->relation as $relation)
  3036. {
  3037. if( $relation[2] == $column )
  3038. {
  3039. $new_column = $table_name.'.'.$column;
  3040. if(isset($this->display_as[$column]))
  3041. {
  3042. $display_as = $this->display_as[$column];
  3043. unset($this->display_as[$column]);
  3044. $this->display_as[$new_column] = $display_as;
  3045. }
  3046. else
  3047. {
  3048. $this->display_as[$new_column] = ucfirst(str_replace('_',' ',$column));
  3049. }
  3050. $column = $new_column;
  3051. $this->columns[$col_num] = $new_column;
  3052. }
  3053. }
  3054. }
  3055. }
  3056. if(isset($this->display_as[$column]))
  3057. $this->columns[$col_num] = (object)array('field_name' => $column, 'display_as' => $this->display_as[$column]);
  3058. elseif(isset($field_types[$column]))
  3059. $this->columns[$col_num] = (object)array('field_name' => $column, 'display_as' => $field_types[$column]->display_as);
  3060. else
  3061. $this->columns[$col_num] = (object)array('field_name' => $column, 'display_as' =>
  3062. ucfirst(str_replace('_',' ',$column)));
  3063. if(!empty($this->unset_columns) && in_array($column,$this->unset_columns))
  3064. {
  3065. unset($this->columns[$col_num]);
  3066. }
  3067. }
  3068. $this->columns_checked = true;
  3069. }
  3070. return $this->columns;
  3071. }
  3072. /**
  3073. *
  3074. * Enter description here ...
  3075. */
  3076. protected function get_add_fields()
  3077. {
  3078. if($this->add_fields_checked === false)
  3079. {
  3080. $field_types = $this->get_field_types();
  3081. if(!empty($this->add_fields))
  3082. {
  3083. foreach($this->add_fields as $field_num => $field)
  3084. {
  3085. if(isset($this->display_as[$field]))
  3086. $this->add_fields[$field_num] = (object)array('field_name' => $field, 'display_as' => $this->display_as[$field]);
  3087. elseif(isset($field_types[$field]->display_as))
  3088. $this->add_fields[$field_num] = (object)array('field_name' => $field, 'display_as' => $field_types[$field]->display_as);
  3089. else
  3090. $this->add_fields[$field_num] = (object)array('field_name' => $field, 'display_as' => ucfirst(str_replace('_',' ',$field)));
  3091. }
  3092. }
  3093. else
  3094. {
  3095. $this->add_fields = array();
  3096. foreach($field_types as $field)
  3097. {
  3098. //Check if an unset_add_field is initialize for this field name
  3099. if($this->unset_add_fields !== null && is_array($this->unset_add_fields) && in_array($field->name,$this->unset_add_fields))
  3100. continue;
  3101. if( (!isset($field->db_extra) || $field->db_extra != 'auto_increment') )
  3102. {
  3103. if(isset($this->display_as[$field->name]))
  3104. $this->add_fields[] = (object)array('field_name' => $field->name, 'display_as' => $this->display_as[$field->name]);
  3105. else
  3106. $this->add_fields[] = (object)array('field_name' => $field->name, 'display_as' => $field->display_as);
  3107. }
  3108. }
  3109. }
  3110. $this->add_fields_checked = true;
  3111. }
  3112. return $this->add_fields;
  3113. }
  3114. /**
  3115. *
  3116. * Enter description here ...
  3117. */
  3118. protected function get_edit_fields()
  3119. {
  3120. if($this->edit_fields_checked === false)
  3121. {
  3122. $field_types = $this->get_field_types();
  3123. if(!empty($this->edit_fields))
  3124. {
  3125. foreach($this->edit_fields as $field_num => $field)
  3126. {
  3127. if(isset($this->display_as[$field]))
  3128. $this->edit_fields[$field_num] = (object)array('field_name' => $field, 'display_as' => $this->display_as[$field]);
  3129. else
  3130. $this->edit_fields[$field_num] = (object)array('field_name' => $field, 'display_as' => $field_types[$field]->display_as);
  3131. }
  3132. }
  3133. else
  3134. {
  3135. $this->edit_fields = array();
  3136. foreach($field_types as $field)
  3137. {
  3138. //Check if an unset_edit_field is initialize for this field name
  3139. if($this->unset_edit_fields !== null && is_array($this->unset_edit_fields) && in_array($field->name,$this->unset_edit_fields))
  3140. continue;
  3141. if(!isset($field->db_extra) || $field->db_extra != 'auto_increment')
  3142. {
  3143. if(isset($this->display_as[$field->name]))
  3144. $this->edit_fields[] = (object)array('field_name' => $field->name, 'display_as' => $this->display_as[$field->name]);
  3145. else
  3146. $this->edit_fields[] = (object)array('field_name' => $field->name, 'display_as' => $field->display_as);
  3147. }
  3148. }
  3149. }
  3150. $this->edit_fields_checked = true;
  3151. }
  3152. return $this->edit_fields;
  3153. }
  3154. public function order_by($order_by, $direction = 'asc')
  3155. {
  3156. $this->order_by = array($order_by,$direction);
  3157. return $this;
  3158. }
  3159. public function where($key, $value = NULL, $escape = TRUE)
  3160. {
  3161. $this->where[] = array($key,$value,$escape);
  3162. return $this;
  3163. }
  3164. public function or_where($key, $value = NULL, $escape = TRUE)
  3165. {
  3166. $this->or_where[] = array($key,$value,$escape);
  3167. return $this;
  3168. }
  3169. public function like($field, $match = '', $side = 'both')
  3170. {
  3171. $this->like[] = array($field, $match, $side);
  3172. return $this;
  3173. }
  3174. protected function having($key, $value = '', $escape = TRUE)
  3175. {
  3176. $this->having[] = array($key, $value, $escape);
  3177. return $this;
  3178. }
  3179. protected function or_having($key, $value = '', $escape = TRUE)
  3180. {
  3181. $this->or_having[] = array($key, $value, $escape);
  3182. return $this;
  3183. }
  3184. public function or_like($field, $match = '', $side = 'both')
  3185. {
  3186. $this->or_like[] = array($field, $match, $side);
  3187. return $this;
  3188. }
  3189. public function limit($limit, $offset = '')
  3190. {
  3191. $this->limit = array($limit,$offset);
  3192. return $this;
  3193. }
  3194. protected function _initialize_helpers()
  3195. {
  3196. $ci = &get_instance();
  3197. $ci->load->helper('url');
  3198. $ci->load->helper('form');
  3199. }
  3200. protected function _initialize_variables()
  3201. {
  3202. $ci = &get_instance();
  3203. $ci->load->config('grocery_crud');
  3204. $this->config = (object)array();
  3205. /** Initialize all the config variables into this object */
  3206. $this->config->default_language = $ci->config->item('grocery_crud_default_language');
  3207. $this->config->date_format = $ci->config->item('grocery_crud_date_format');
  3208. $this->config->default_per_page = $ci->config->item('grocery_crud_default_per_page');
  3209. $this->config->file_upload_allow_file_types = $ci->config->item('grocery_crud_file_upload_allow_file_types');
  3210. $this->config->file_upload_max_file_size = $ci->config->item('grocery_crud_file_upload_max_file_size');
  3211. $this->config->default_text_editor = $ci->config->item('grocery_crud_default_text_editor');
  3212. $this->config->text_editor_type = $ci->config->item('grocery_crud_text_editor_type');
  3213. $this->config->character_limiter = $ci->config->item('grocery_crud_character_limiter');
  3214. /** Initialize default paths */
  3215. $this->default_javascript_path = $this->default_assets_path.'/js';
  3216. $this->default_css_path = $this->default_assets_path.'/css';
  3217. $this->default_texteditor_path = $this->default_assets_path.'/texteditor';
  3218. $this->default_theme_path = $this->default_assets_path.'/themes';
  3219. $this->character_limiter = $this->config->character_limiter;
  3220. if($this->character_limiter === 0 || $this->character_limiter === '0')
  3221. {
  3222. $this->character_limiter = 1000000; //a big number
  3223. }
  3224. elseif($this->character_limiter === null || $this->character_limiter === false)
  3225. {
  3226. $this->character_limiter = 30; //is better to have the number 30 rather than the 0 value
  3227. }
  3228. }
  3229. protected function _set_primary_keys_to_model()
  3230. {
  3231. if(!empty($this->primary_keys))
  3232. {
  3233. foreach($this->primary_keys as $primary_key)
  3234. {
  3235. $this->basic_model->set_primary_key($primary_key['field_name'],$primary_key['table_name']);
  3236. }
  3237. }
  3238. }
  3239. /**
  3240. * Initialize all the required libraries and variables before rendering
  3241. */
  3242. protected function pre_render()
  3243. {
  3244. $this->_initialize_variables();
  3245. $this->_initialize_helpers();
  3246. $this->_load_language();
  3247. $this->state_code = $this->getStateCode();
  3248. if($this->basic_model === null)
  3249. $this->set_default_Model();
  3250. $this->set_basic_db_table($this->get_table());
  3251. $this->_load_date_format();
  3252. $this->_set_primary_keys_to_model();
  3253. }
  3254. /**
  3255. *
  3256. * Or else ... make it work! The web application takes decision of what to do and show it to the final user.
  3257. * Without this function nothing works. Here is the core of grocery CRUD project.
  3258. *
  3259. * @access public
  3260. */
  3261. public function render()
  3262. {
  3263. $this->pre_render();
  3264. if( $this->state_code != 0 )
  3265. {
  3266. $this->state_info = $this->getStateInfo();
  3267. }
  3268. else
  3269. {
  3270. throw new Exception('The state is unknown , I don\'t know what I will do with your data!', 4);
  3271. die();
  3272. }
  3273. switch ($this->state_code) {
  3274. case 15://success
  3275. case 1://list
  3276. if($this->unset_list)
  3277. {
  3278. throw new Exception('You don\'t have permissions for this operation', 14);
  3279. die();
  3280. }
  3281. if($this->theme === null)
  3282. $this->set_theme($this->default_theme);
  3283. $this->setThemeBasics();
  3284. $this->set_basic_Layout();
  3285. $state_info = $this->getStateInfo();
  3286. $this->showList(false,$state_info);
  3287. break;
  3288. case 2://add
  3289. if($this->unset_add)
  3290. {
  3291. throw new Exception('You don\'t have permissions for this operation', 14);
  3292. die();
  3293. }
  3294. if($this->theme === null)
  3295. $this->set_theme($this->default_theme);
  3296. $this->setThemeBasics();
  3297. $this->set_basic_Layout();
  3298. $this->showAddForm();
  3299. break;
  3300. case 3://edit
  3301. if($this->unset_edit)
  3302. {
  3303. throw new Exception('You don\'t have permissions for this operation', 14);
  3304. die();
  3305. }
  3306. if($this->theme === null)
  3307. $this->set_theme($this->default_theme);
  3308. $this->setThemeBasics();
  3309. $this->set_basic_Layout();
  3310. $state_info = $this->getStateInfo();
  3311. $this->showEditForm($state_info);
  3312. break;
  3313. case 4://delete
  3314. if($this->unset_delete)
  3315. {
  3316. throw new Exception('This user is not allowed to do this operation', 14);
  3317. die();
  3318. }
  3319. $state_info = $this->getStateInfo();
  3320. $delete_result = $this->db_delete($state_info);
  3321. $this->delete_layout( $delete_result );
  3322. break;
  3323. case 5://insert
  3324. if($this->unset_add)
  3325. {
  3326. throw new Exception('This user is not allowed to do this operation', 14);
  3327. die();
  3328. }
  3329. $state_info = $this->getStateInfo();
  3330. $insert_result = $this->db_insert($state_info);
  3331. $this->insert_layout($insert_result);
  3332. break;
  3333. case 6://update
  3334. if($this->unset_edit)
  3335. {
  3336. throw new Exception('This user is not allowed to do this operation', 14);
  3337. die();
  3338. }
  3339. $state_info = $this->getStateInfo();
  3340. $update_result = $this->db_update($state_info);
  3341. $this->update_layout( $update_result,$state_info);
  3342. break;
  3343. case 7://ajax_list
  3344. if($this->unset_list)
  3345. {
  3346. throw new Exception('You don\'t have permissions for this operation', 14);
  3347. die();
  3348. }
  3349. if($this->theme === null)
  3350. $this->set_theme($this->default_theme);
  3351. $this->setThemeBasics();
  3352. $this->set_basic_Layout();
  3353. $state_info = $this->getStateInfo();
  3354. $this->set_ajax_list_queries($state_info);
  3355. $this->showList(true);
  3356. break;
  3357. case 8://ajax_list_info
  3358. if($this->theme === null)
  3359. $this->set_theme($this->default_theme);
  3360. $this->setThemeBasics();
  3361. $this->set_basic_Layout();
  3362. $state_info = $this->getStateInfo();
  3363. $this->set_ajax_list_queries($state_info);
  3364. $this->showListInfo();
  3365. break;
  3366. case 9://insert_validation
  3367. $validation_result = $this->db_insert_validation();
  3368. $this->validation_layout($validation_result);
  3369. break;
  3370. case 10://update_validation
  3371. $validation_result = $this->db_update_validation();
  3372. $this->validation_layout($validation_result);
  3373. break;
  3374. case 11://upload_file
  3375. $state_info = $this->getStateInfo();
  3376. $upload_result = $this->upload_file($state_info);
  3377. $this->upload_layout($upload_result, $state_info->field_name);
  3378. break;
  3379. case 12://delete_file
  3380. $state_info = $this->getStateInfo();
  3381. $delete_file_result = $this->delete_file($state_info);
  3382. $this->delete_file_layout($delete_file_result);
  3383. break;
  3384. /*
  3385. case 13: //ajax_relation
  3386. $state_info = $this->getStateInfo();
  3387. $ajax_relation_result = $this->ajax_relation($state_info);
  3388. $ajax_relation_result[""] = "";
  3389. echo json_encode($ajax_relation_result);
  3390. die();
  3391. break;
  3392. case 14: //ajax_relation_n_n
  3393. echo json_encode(array("34" => 'Johnny' , "78" => "Test"));
  3394. die();
  3395. break;
  3396. */
  3397. case 16: //export to excel
  3398. //a big number just to ensure that the table characters will not be cutted.
  3399. $this->character_limiter = 1000000;
  3400. if($this->unset_export)
  3401. {
  3402. throw new Exception('You don\'t have permissions for this operation', 15);
  3403. die();
  3404. }
  3405. if($this->theme === null)
  3406. $this->set_theme($this->default_theme);
  3407. $this->setThemeBasics();
  3408. $this->set_basic_Layout();
  3409. $state_info = $this->getStateInfo();
  3410. $this->set_ajax_list_queries($state_info);
  3411. $this->exportToExcel($state_info);
  3412. break;
  3413. case 17: //print
  3414. //a big number just to ensure that the table characters will not be cutted.
  3415. $this->character_limiter = 1000000;
  3416. if($this->unset_print)
  3417. {
  3418. throw new Exception('You don\'t have permissions for this operation', 15);
  3419. die();
  3420. }
  3421. if($this->theme === null)
  3422. $this->set_theme($this->default_theme);
  3423. $this->setThemeBasics();
  3424. $this->set_basic_Layout();
  3425. $state_info = $this->getStateInfo();
  3426. $this->set_ajax_list_queries($state_info);
  3427. $this->print_webpage($state_info);
  3428. break;
  3429. }
  3430. return $this->get_layout();
  3431. }
  3432. protected function get_common_data()
  3433. {
  3434. $data = (object)array();
  3435. $data->subject = $this->subject;
  3436. $data->subject_plural = $this->subject_plural;
  3437. return $data;
  3438. }
  3439. /**
  3440. *
  3441. * Enter description here ...
  3442. */
  3443. public function callback_before_insert($callback = null)
  3444. {
  3445. $this->callback_before_insert = $callback;
  3446. return $this;
  3447. }
  3448. /**
  3449. *
  3450. * Enter description here ...
  3451. */
  3452. public function callback_after_insert($callback = null)
  3453. {
  3454. $this->callback_after_insert = $callback;
  3455. return $this;
  3456. }
  3457. /**
  3458. *
  3459. * Enter description here ...
  3460. */
  3461. public function callback_insert($callback = null)
  3462. {
  3463. $this->callback_insert = $callback;
  3464. return $this;
  3465. }
  3466. /**
  3467. *
  3468. * Enter description here ...
  3469. */
  3470. public function callback_before_update($callback = null)
  3471. {
  3472. $this->callback_before_update = $callback;
  3473. return $this;
  3474. }
  3475. /**
  3476. *
  3477. * Enter description here ...
  3478. */
  3479. public function callback_after_update($callback = null)
  3480. {
  3481. $this->callback_after_update = $callback;
  3482. return $this;
  3483. }
  3484. /**
  3485. *
  3486. * Enter description here ...
  3487. * @param mixed $callback
  3488. */
  3489. public function callback_update($callback = null)
  3490. {
  3491. $this->callback_update = $callback;
  3492. return $this;
  3493. }
  3494. /**
  3495. *
  3496. * Enter description here ...
  3497. */
  3498. public function callback_before_delete($callback = null)
  3499. {
  3500. $this->callback_before_delete = $callback;
  3501. return $this;
  3502. }
  3503. /**
  3504. *
  3505. * Enter description here ...
  3506. */
  3507. public function callback_after_delete($callback = null)
  3508. {
  3509. $this->callback_after_delete = $callback;
  3510. return $this;
  3511. }
  3512. /**
  3513. *
  3514. * Enter description here ...
  3515. */
  3516. public function callback_delete($callback = null)
  3517. {
  3518. $this->callback_delete = $callback;
  3519. return $this;
  3520. }
  3521. /**
  3522. *
  3523. * Enter description here ...
  3524. * @param string $column
  3525. * @param mixed $callback
  3526. */
  3527. public function callback_column($column ,$callback = null)
  3528. {
  3529. $this->callback_column[$column] = $callback;
  3530. return $this;
  3531. }
  3532. /**
  3533. *
  3534. * Enter description here ...
  3535. * @param string $field
  3536. * @param mixed $callback
  3537. */
  3538. public function callback_field($field, $callback = null)
  3539. {
  3540. $this->callback_add_field[$field] = $callback;
  3541. $this->callback_edit_field[$field] = $callback;
  3542. return $this;
  3543. }
  3544. /**
  3545. *
  3546. * Enter description here ...
  3547. * @param string $field
  3548. * @param mixed $callback
  3549. */
  3550. public function callback_add_field($field, $callback = null)
  3551. {
  3552. $this->callback_add_field[$field] = $callback;
  3553. return $this;
  3554. }
  3555. /**
  3556. *
  3557. * Enter description here ...
  3558. * @param string $field
  3559. * @param mixed $callback
  3560. */
  3561. public function callback_edit_field($field, $callback = null)
  3562. {
  3563. $this->callback_edit_field[$field] = $callback;
  3564. return $this;
  3565. }
  3566. /**
  3567. *
  3568. * Callback that replace the default auto uploader
  3569. *
  3570. * @param mixed $callback
  3571. * @return grocery_CRUD
  3572. */
  3573. public function callback_upload($callback = null)
  3574. {
  3575. $this->callback_upload = $callback;
  3576. return $this;
  3577. }
  3578. /**
  3579. *
  3580. * A callback that triggered before the upload functionality. This callback is suggested for validation checks
  3581. * @param mixed $callback
  3582. * @return grocery_CRUD
  3583. */
  3584. public function callback_before_upload($callback = null)
  3585. {
  3586. $this->callback_before_upload = $callback;
  3587. return $this;
  3588. }
  3589. /**
  3590. *
  3591. * A callback that triggered after the upload functionality
  3592. * @param mixed $callback
  3593. * @return grocery_CRUD
  3594. */
  3595. public function callback_after_upload($callback = null)
  3596. {
  3597. $this->callback_after_upload = $callback;
  3598. return $this;
  3599. }
  3600. /**
  3601. *
  3602. * Gets the basic database table of our crud.
  3603. * @return string
  3604. */
  3605. public function get_table()
  3606. {
  3607. if($this->basic_db_table_checked)
  3608. {
  3609. return $this->basic_db_table;
  3610. }
  3611. elseif( $this->basic_db_table !== null )
  3612. {
  3613. if(!$this->table_exists($this->basic_db_table))
  3614. {
  3615. throw new Exception('The table name does not exist. Please check you database and try again.',11);
  3616. die();
  3617. }
  3618. $this->basic_db_table_checked = true;
  3619. return $this->basic_db_table;
  3620. }
  3621. else
  3622. {
  3623. //Last try , try to find the table from your view / function name!!! Not suggested but it works .
  3624. $last_chance_table_name = $this->get_method_name();
  3625. if($this->table_exists($last_chance_table_name))
  3626. {
  3627. $this->set_table($last_chance_table_name);
  3628. }
  3629. $this->basic_db_table_checked = true;
  3630. return $this->basic_db_table;
  3631. }
  3632. return false;
  3633. }
  3634. /**
  3635. *
  3636. * The field names of the required fields
  3637. */
  3638. public function required_fields()
  3639. {
  3640. $args = func_get_args();
  3641. if(isset($args[0]) && is_array($args[0]))
  3642. {
  3643. $args = $args[0];
  3644. }
  3645. $this->required_fields = $args;
  3646. return $this;
  3647. }
  3648. /**
  3649. *
  3650. * Sets the basic database table that we will get our data.
  3651. * @param string $table_name
  3652. * @return grocery_CRUD
  3653. */
  3654. public function set_table($table_name)
  3655. {
  3656. if(!empty($table_name) && $this->basic_db_table === null)
  3657. {
  3658. $this->basic_db_table = $table_name;
  3659. }
  3660. elseif(!empty($table_name))
  3661. {
  3662. throw new Exception('You have already insert a table name once...', 1);
  3663. }
  3664. else
  3665. {
  3666. throw new Exception('The table name cannot be empty.', 2);
  3667. die();
  3668. }
  3669. return $this;
  3670. }
  3671. /**
  3672. *
  3673. * Set a subject to understand what type of CRUD you use.
  3674. * @example In this CRUD we work with the table db_categories. The $subject will be the 'Category'
  3675. * @param string $subject
  3676. * @param bool $has_plural
  3677. * @return grocery_CRUD
  3678. */
  3679. public function set_subject( $subject )
  3680. {
  3681. $this->subject = $subject;
  3682. $this->subject_plural = $subject;
  3683. return $this;
  3684. }
  3685. /**
  3686. *
  3687. * Enter description here ...
  3688. * @param $title
  3689. * @param $image_url
  3690. * @param $url
  3691. * @param $css_class
  3692. * @param $url_callback
  3693. */
  3694. public function add_action( $label, $image_url = '', $link_url = '', $css_class = '', $url_callback = null)
  3695. {
  3696. $unique_id = substr($label,0,1).substr(md5($label.$link_url),-8); //The unique id is used for class name so it must begin with a string
  3697. $this->actions[$unique_id] = (object)array(
  3698. 'label' => $label,
  3699. 'image_url' => $image_url,
  3700. 'link_url' => $link_url,
  3701. 'css_class' => $css_class,
  3702. 'url_callback' => $url_callback,
  3703. 'url_has_http' => substr($link_url,0,7) == 'http://' ? true : false
  3704. );
  3705. return $this;
  3706. }
  3707. /**
  3708. *
  3709. * Set a simple 1-n foreign key relation
  3710. * @param string $field_name
  3711. * @param string $related_table
  3712. * @param string $related_title_field
  3713. * @param mixed $where_clause
  3714. * @param string $order_by
  3715. */
  3716. public function set_relation($field_name , $related_table, $related_title_field, $where_clause = null, $order_by = null)
  3717. {
  3718. $this->relation[$field_name] = array($field_name, $related_table,$related_title_field, $where_clause, $order_by);
  3719. return $this;
  3720. }
  3721. /**
  3722. *
  3723. * Sets a relation with n-n relationship.
  3724. * @param string $field_name
  3725. * @param string $relation_table
  3726. * @param string $selection_table
  3727. * @param string $primary_key_alias_to_this_table
  3728. * @param string $primary_key_alias_to_selection_table
  3729. * @param string $title_field_selection_table
  3730. * @param string $priority_field_relation_table
  3731. * @param mixed $where_clause
  3732. */
  3733. public function set_relation_n_n($field_name, $relation_table, $selection_table, $primary_key_alias_to_this_table, $primary_key_alias_to_selection_table , $title_field_selection_table , $priority_field_relation_table = null, $where_clause = null)
  3734. {
  3735. $this->relation_n_n[$field_name] =
  3736. (object)array(
  3737. 'field_name' => $field_name,
  3738. 'relation_table' => $relation_table,
  3739. 'selection_table' => $selection_table,
  3740. 'primary_key_alias_to_this_table' => $primary_key_alias_to_this_table,
  3741. 'primary_key_alias_to_selection_table' => $primary_key_alias_to_selection_table ,
  3742. 'title_field_selection_table' => $title_field_selection_table ,
  3743. 'priority_field_relation_table' => $priority_field_relation_table,
  3744. 'where_clause' => $where_clause
  3745. );
  3746. return $this;
  3747. }
  3748. /**
  3749. *
  3750. * Transform a field to an upload field
  3751. *
  3752. * @param string $field_name
  3753. * @param string $upload_path
  3754. */
  3755. public function set_field_upload($field_name, $upload_dir = null)
  3756. {
  3757. $upload_dir = substr($upload_dir,-1,1) == '/' ? substr($upload_dir,0,-1) : $upload_dir;
  3758. $this->upload_fields[$field_name] = (object)array( 'field_name' => $field_name , 'upload_path' => $upload_dir, 'encrypted_field_name' => $this->_unique_field_name($field_name));
  3759. return $this;
  3760. }
  3761. }
  3762. if(defined('CI_VERSION'))
  3763. {
  3764. $ci = &get_instance();
  3765. $ci->load->library('Form_validation');
  3766. class grocery_CRUD_Form_validation extends CI_Form_validation{
  3767. public $CI;
  3768. public $_field_data = array();
  3769. public $_config_rules = array();
  3770. public $_error_array = array();
  3771. public $_error_messages = array();
  3772. public $_error_prefix = '<p>';
  3773. public $_error_suffix = '</p>';
  3774. public $error_string = '';
  3775. public $_safe_form_data = FALSE;
  3776. }
  3777. }
  3778. /*
  3779. * jQuery File Upload Plugin PHP Example 5.5
  3780. * https://github.com/blueimp/jQuery-File-Upload
  3781. *
  3782. * Copyright 2010, Sebastian Tschan
  3783. * https://blueimp.net
  3784. *
  3785. * Licensed under the MIT license:
  3786. * http://www.opensource.org/licenses/MIT
  3787. */
  3788. class UploadHandler
  3789. {
  3790. private $options;
  3791. public $default_config_path = null;
  3792. function __construct($options=null) {
  3793. $this->options = array(
  3794. 'script_url' => $this->getFullUrl().'/'.basename(__FILE__),
  3795. 'upload_dir' => dirname(__FILE__).'/files/',
  3796. 'upload_url' => $this->getFullUrl().'/files/',
  3797. 'param_name' => 'files',
  3798. // The php.ini settings upload_max_filesize and post_max_size
  3799. // take precedence over the following max_file_size setting:
  3800. 'max_file_size' => null,
  3801. 'min_file_size' => 1,
  3802. 'accept_file_types' => '/.+$/i',
  3803. 'max_number_of_files' => null,
  3804. // Set the following option to false to enable non-multipart uploads:
  3805. 'discard_aborted_uploads' => true,
  3806. // Set to true to rotate images based on EXIF meta data, if available:
  3807. 'orient_image' => false,
  3808. 'image_versions' => array(
  3809. // Uncomment the following version to restrict the size of
  3810. // uploaded images. You can also add additional versions with
  3811. // their own upload directories:
  3812. /*
  3813. 'large' => array(
  3814. 'upload_dir' => dirname(__FILE__).'/files/',
  3815. 'upload_url' => dirname($_SERVER['PHP_SELF']).'/files/',
  3816. 'max_width' => 1920,
  3817. 'max_height' => 1200
  3818. ),
  3819. 'thumbnail' => array(
  3820. 'upload_dir' => dirname(__FILE__).'/thumbnails/',
  3821. 'upload_url' => $this->getFullUrl().'/thumbnails/',
  3822. 'max_width' => 80,
  3823. 'max_height' => 80
  3824. )
  3825. */
  3826. )
  3827. );
  3828. if ($options) {
  3829. // Or else for PHP >= 5.3.0 use: $this->options = array_replace_recursive($this->options, $options);
  3830. foreach($options as $option_name => $option)
  3831. {
  3832. $this->options[$option_name] = $option;
  3833. }
  3834. }
  3835. }
  3836. function getFullUrl() {
  3837. return
  3838. (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').
  3839. (isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
  3840. (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
  3841. (isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] === 443 ||
  3842. $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
  3843. substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
  3844. }
  3845. private function get_file_object($file_name) {
  3846. $file_path = $this->options['upload_dir'].$file_name;
  3847. if (is_file($file_path) && $file_name[0] !== '.') {
  3848. $file = new stdClass();
  3849. $file->name = $file_name;
  3850. $file->size = filesize($file_path);
  3851. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  3852. foreach($this->options['image_versions'] as $version => $options) {
  3853. if (is_file($options['upload_dir'].$file_name)) {
  3854. $file->{$version.'_url'} = $options['upload_url']
  3855. .rawurlencode($file->name);
  3856. }
  3857. }
  3858. $file->delete_url = $this->options['script_url']
  3859. .'?file='.rawurlencode($file->name);
  3860. $file->delete_type = 'DELETE';
  3861. return $file;
  3862. }
  3863. return null;
  3864. }
  3865. private function get_file_objects() {
  3866. return array_values(array_filter(array_map(
  3867. array($this, 'get_file_object'),
  3868. scandir($this->options['upload_dir'])
  3869. )));
  3870. }
  3871. private function create_scaled_image($file_name, $options) {
  3872. $file_path = $this->options['upload_dir'].$file_name;
  3873. $new_file_path = $options['upload_dir'].$file_name;
  3874. list($img_width, $img_height) = @getimagesize($file_path);
  3875. if (!$img_width || !$img_height) {
  3876. return false;
  3877. }
  3878. $scale = min(
  3879. $options['max_width'] / $img_width,
  3880. $options['max_height'] / $img_height
  3881. );
  3882. if ($scale > 1) {
  3883. $scale = 1;
  3884. }
  3885. $new_width = $img_width * $scale;
  3886. $new_height = $img_height * $scale;
  3887. $new_img = @imagecreatetruecolor($new_width, $new_height);
  3888. switch (strtolower(substr(strrchr($file_name, '.'), 1))) {
  3889. case 'jpg':
  3890. case 'jpeg':
  3891. $src_img = @imagecreatefromjpeg($file_path);
  3892. $write_image = 'imagejpeg';
  3893. break;
  3894. case 'gif':
  3895. @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
  3896. $src_img = @imagecreatefromgif($file_path);
  3897. $write_image = 'imagegif';
  3898. break;
  3899. case 'png':
  3900. @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
  3901. @imagealphablending($new_img, false);
  3902. @imagesavealpha($new_img, true);
  3903. $src_img = @imagecreatefrompng($file_path);
  3904. $write_image = 'imagepng';
  3905. break;
  3906. default:
  3907. $src_img = $image_method = null;
  3908. }
  3909. $success = $src_img && @imagecopyresampled(
  3910. $new_img,
  3911. $src_img,
  3912. 0, 0, 0, 0,
  3913. $new_width,
  3914. $new_height,
  3915. $img_width,
  3916. $img_height
  3917. ) && $write_image($new_img, $new_file_path);
  3918. // Free up memory (imagedestroy does not delete files):
  3919. @imagedestroy($src_img);
  3920. @imagedestroy($new_img);
  3921. return $success;
  3922. }
  3923. private function has_error($uploaded_file, $file, $error) {
  3924. if ($error) {
  3925. return $error;
  3926. }
  3927. if (!preg_match($this->options['accept_file_types'], $file->name)) {
  3928. return 'acceptFileTypes';
  3929. }
  3930. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  3931. $file_size = filesize($uploaded_file);
  3932. } else {
  3933. $file_size = $_SERVER['CONTENT_LENGTH'];
  3934. }
  3935. if ($this->options['max_file_size'] && (
  3936. $file_size > $this->options['max_file_size'] ||
  3937. $file->size > $this->options['max_file_size'])
  3938. ) {
  3939. return 'maxFileSize';
  3940. }
  3941. if ($this->options['min_file_size'] &&
  3942. $file_size < $this->options['min_file_size']) {
  3943. return 'minFileSize';
  3944. }
  3945. if (is_int($this->options['max_number_of_files']) && (
  3946. count($this->get_file_objects()) >= $this->options['max_number_of_files'])
  3947. ) {
  3948. return 'maxNumberOfFiles';
  3949. }
  3950. return $error;
  3951. }
  3952. private function trim_file_name($name, $type) {
  3953. // Remove path information and dots around the filename, to prevent uploading
  3954. // into different directories or replacing hidden system files.
  3955. // Also remove control characters and spaces (\x00..\x20) around the filename:
  3956. $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
  3957. // Add missing file extension for known image types:
  3958. if (strpos($file_name, '.') === false &&
  3959. preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
  3960. $file_name .= '.'.$matches[1];
  3961. }
  3962. //Ensure that we don't have disallowed characters and add a unique id just to ensure that the file name will be unique
  3963. $file_name = substr(uniqid(),-5).'-'.$this->_transliterate_characters($file_name);
  3964. return $file_name;
  3965. }
  3966. private function _transliterate_characters($file_name)
  3967. {
  3968. include($this->default_config_path.'/translit_chars.php');
  3969. if ( ! isset($translit_characters))
  3970. {
  3971. return preg_replace("/([^a-zA-Z0-9\.\-\_]+?){1}/i", '-', $file_name);
  3972. }
  3973. $transformed_file_name = preg_replace(array_keys($translit_characters), array_values($translit_characters), $file_name);
  3974. return str_replace(" ", "-", $transformed_file_name);
  3975. }
  3976. private function orient_image($file_path) {
  3977. $exif = exif_read_data($file_path);
  3978. $orientation = intval(@$exif['Orientation']);
  3979. if (!in_array($orientation, array(3, 6, 8))) {
  3980. return false;
  3981. }
  3982. $image = @imagecreatefromjpeg($file_path);
  3983. switch ($orientation) {
  3984. case 3:
  3985. $image = @imagerotate($image, 180, 0);
  3986. break;
  3987. case 6:
  3988. $image = @imagerotate($image, 270, 0);
  3989. break;
  3990. case 8:
  3991. $image = @imagerotate($image, 90, 0);
  3992. break;
  3993. default:
  3994. return false;
  3995. }
  3996. $success = imagejpeg($image, $file_path);
  3997. // Free up memory (imagedestroy does not delete files):
  3998. @imagedestroy($image);
  3999. return $success;
  4000. }
  4001. private function handle_file_upload($uploaded_file, $name, $size, $type, $error) {
  4002. $file = new stdClass();
  4003. $file->name = $this->trim_file_name($name, $type);
  4004. $file->size = intval($size);
  4005. $file->type = $type;
  4006. $error = $this->has_error($uploaded_file, $file, $error);
  4007. if (!$error && $file->name) {
  4008. $file_path = $this->options['upload_dir'].$file->name;
  4009. $append_file = !$this->options['discard_aborted_uploads'] &&
  4010. is_file($file_path) && $file->size > filesize($file_path);
  4011. clearstatcache();
  4012. if ($uploaded_file && is_uploaded_file($uploaded_file)) {
  4013. // multipart/formdata uploads (POST method uploads)
  4014. if ($append_file) {
  4015. file_put_contents(
  4016. $file_path,
  4017. fopen($uploaded_file, 'r'),
  4018. FILE_APPEND
  4019. );
  4020. } else {
  4021. move_uploaded_file($uploaded_file, $file_path);
  4022. }
  4023. } else {
  4024. // Non-multipart uploads (PUT method support)
  4025. file_put_contents(
  4026. $file_path,
  4027. fopen('php://input', 'r'),
  4028. $append_file ? FILE_APPEND : 0
  4029. );
  4030. }
  4031. $file_size = filesize($file_path);
  4032. if ($file_size === $file->size) {
  4033. if ($this->options['orient_image']) {
  4034. $this->orient_image($file_path);
  4035. }
  4036. $file->url = $this->options['upload_url'].rawurlencode($file->name);
  4037. foreach($this->options['image_versions'] as $version => $options) {
  4038. if ($this->create_scaled_image($file->name, $options)) {
  4039. $file->{$version.'_url'} = $options['upload_url']
  4040. .rawurlencode($file->name);
  4041. }
  4042. }
  4043. } else if ($this->options['discard_aborted_uploads']) {
  4044. unlink($file_path);
  4045. $file->error = 'abort';
  4046. }
  4047. $file->size = $file_size;
  4048. $file->delete_url = $this->options['script_url']
  4049. .'?file='.rawurlencode($file->name);
  4050. $file->delete_type = 'DELETE';
  4051. } else {
  4052. $file->error = $error;
  4053. }
  4054. return $file;
  4055. }
  4056. public function get() {
  4057. $file_name = isset($_REQUEST['file']) ?
  4058. basename(stripslashes($_REQUEST['file'])) : null;
  4059. if ($file_name) {
  4060. $info = $this->get_file_object($file_name);
  4061. } else {
  4062. $info = $this->get_file_objects();
  4063. }
  4064. header('Content-type: application/json');
  4065. echo json_encode($info);
  4066. }
  4067. public function post() {
  4068. if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
  4069. return $this->delete();
  4070. }
  4071. $upload = isset($_FILES[$this->options['param_name']]) ?
  4072. $_FILES[$this->options['param_name']] : null;
  4073. $info = array();
  4074. if ($upload && is_array($upload['tmp_name'])) {
  4075. foreach ($upload['tmp_name'] as $index => $value) {
  4076. $info[] = $this->handle_file_upload(
  4077. $upload['tmp_name'][$index],
  4078. isset($_SERVER['HTTP_X_FILE_NAME']) ?
  4079. $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
  4080. isset($_SERVER['HTTP_X_FILE_SIZE']) ?
  4081. $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
  4082. isset($_SERVER['HTTP_X_FILE_TYPE']) ?
  4083. $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
  4084. $upload['error'][$index]
  4085. );
  4086. }
  4087. } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
  4088. $info[] = $this->handle_file_upload(
  4089. isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
  4090. isset($_SERVER['HTTP_X_FILE_NAME']) ?
  4091. $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
  4092. isset($_SERVER['HTTP_X_FILE_SIZE']) ?
  4093. $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
  4094. isset($_SERVER['HTTP_X_FILE_TYPE']) ?
  4095. $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
  4096. isset($upload['error']) ? $upload['error'] : null
  4097. );
  4098. }
  4099. header('Vary: Accept');
  4100. $redirect = isset($_REQUEST['redirect']) ?
  4101. stripslashes($_REQUEST['redirect']) : null;
  4102. if ($redirect) {
  4103. header('Location: '.sprintf($redirect, rawurlencode($json)));
  4104. return;
  4105. }
  4106. if (isset($_SERVER['HTTP_ACCEPT']) &&
  4107. (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
  4108. header('Content-type: application/json');
  4109. } else {
  4110. header('Content-type: text/plain');
  4111. }
  4112. return $info;
  4113. }
  4114. public function delete() {
  4115. $file_name = isset($_REQUEST['file']) ?
  4116. basename(stripslashes($_REQUEST['file'])) : null;
  4117. $file_path = $this->options['upload_dir'].$file_name;
  4118. $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
  4119. if ($success) {
  4120. foreach($this->options['image_versions'] as $version => $options) {
  4121. $file = $options['upload_dir'].$file_name;
  4122. if (is_file($file)) {
  4123. unlink($file);
  4124. }
  4125. }
  4126. }
  4127. header('Content-type: application/json');
  4128. echo json_encode($success);
  4129. }
  4130. }