action.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. /** CONTACT / CONTACT **/
  3. //Récuperation d'une liste de contact
  4. Action::register('example_contact_search',function(&$response){
  5. global $_,$myUser,$conf,$myFirm;
  6. User::check_access('example','read');
  7. require_once(__DIR__.SLASH.'ContactExample.class.php');
  8. // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
  9. $query = 'SELECT main.*,'.Firm::joinString('fi').' FROM '.ContactExample::tableName().' main LEFT JOIN '.Firm::tableName().' fi ON main.firm=fi.id WHERE 1';
  10. //selection des colonnes à récuperer
  11. // le premier argument contient toutes les colonnes possibles, le second les colonnes non choisies
  12. column_secure_query(ContactExample::fields(),$_,$query);
  13. $data = $allowedFields = array();
  14. //ajout des champs dynamiques dans la recherche
  15. if($myFirm->has_plugin('fr.core.dynamicform')){
  16. Plugin::need('dynamicform/DynamicForm');
  17. //le premier argument contient le slug du formulaire contenant toutes les colonnes possibles, le second les colonnes non choisies,la requete, l'alias si nécessaire
  18. $dynamicFields = DynamicForm::list('fiche-example');
  19. DynamicForm::query_column_add($dynamicFields,$query,'main');
  20. //On récupère les types de champs qui possèdent une propriété onLoad afin de l'appliquer si on a un champ dynamique
  21. $fieldTypes = array();
  22. foreach($dynamicFields as $field){
  23. $fieldTypes[$field['slug']] = $field['type'];
  24. $allowedFields[] = 'dynamicField_'.$field['id'].'.value';
  25. }
  26. }
  27. //Recherche simple
  28. if(!empty($_['filters']['keyword'])){
  29. $query .= ' AND main.label LIKE ?';
  30. $data[] = '%'.$_['filters']['keyword'].'%';
  31. }
  32. //Recherche avancée
  33. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array_merge($allowedFields,array('main.label','main.phone','main.birth','main.hour','main.firm','main.manager','main.address','main.properties','main.vehicle','main.storyshort','main.story','main.password','main.icon','main.available','main.solvability','main.handicap','main.childs','main.size','main.color','main.salary','main.orientation','main.website','main.mail','main.mobile')),$query,$data);
  34. //Tri des colonnes
  35. if(isset($_['sort'])) sort_secure_query($_['sort'],array_merge($allowedFields,array('main.label','main.phone','main.birth','main.hour','main.firm','main.manager','main.address','main.properties','main.vehicle','main.storyshort','main.story','main.password','main.icon','main.available','main.solvability','main.handicap','main.childs','main.size','main.color','main.salary','main.orientation','main.website','main.mail','main.mobile')),$query,$data);
  36. //Pagination
  37. //Par défaut pour une recherche, 20 items, pour un export 5000 max
  38. $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
  39. //force le nombre de page max a 50 coté serveur
  40. $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
  41. if($_['export'] == 'true') $itemPerPage = 5000;
  42. $response['pagination'] = ContactExample::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
  43. $contacts = ContactExample::staticQuery($query,$data,true,1);
  44. $vehicleList = Dictionary::slugToArray('example_contact_vehicle',true);
  45. $handicapList = Dictionary::slugToArray('example_contact_handicap',true);
  46. $response['rows'] = array();
  47. //Mise en forme des résultats
  48. foreach($contacts as $contact){
  49. $row = $contact->toArray();
  50. $row['birth-readable'] = complete_date($row['birth']).' à '.date('H:i',$row['birth']);
  51. $user = User::byLogin($row['manager']);
  52. $row['manager'] = $user->toArray();
  53. $row['manager']['fullname'] = $user->fullname();
  54. $row['manager']['avatar'] = $user->getAvatar();
  55. $row['firm'] = $contact->join('firm')->toArray();
  56. $row['vehicle'] = isset($vehicleList[$row['vehicle']]) ? $vehicleList[$row['vehicle']] : new Dictionary();
  57. $row['handicaps'] = array();
  58. foreach(explode(',',$row['handicap']) as $id){
  59. if(empty($id)) continue;
  60. $row['handicaps'][] = isset($handicapList[$id]) ? $handicapList[$id] : new Dictionary();
  61. }
  62. $row['properties'] = explode(',',$row['properties']);
  63. $row['story'] = html_entity_decode($row['story']);
  64. $row['solvability'] = ContactExample::solvabilities($row['solvability']);
  65. $row['orientation'] = ContactExample::orientations($row['orientation']);
  66. $row['cv'] = array();
  67. foreach (glob(File::dir().'example'.SLASH.'contact'.SLASH.$row['id'].'/cv/*') as $file) {
  68. $row['cv'][] = array(
  69. 'label' => basename($file),
  70. 'url' => 'action.php?action=example_contact_cv&type=download&path='.base64_encode('example/contact/'.$row['id'].'/cv/'.basename($file)),
  71. );
  72. }
  73. $row['avatar'] = 'action.php?action=example_contact_avatar&type=download&path='.base64_encode('example/contact/'.$row['id'].'/avatar.*');
  74. if($_['export'] == 'true'){
  75. $row['created'] = date('d-m-Y',$row['created']);
  76. $row['updated'] = date('d-m-Y',$row['updated']);
  77. }
  78. //Gestion des champs dynamiques
  79. if($myFirm->has_plugin('fr.core.dynamicform'))
  80. DynamicForm::search_values($row,array(
  81. 'slugs' => $contact->foreign(),
  82. 'types' => $fieldTypes,
  83. 'scope' => 'contact',
  84. ));
  85. $response['rows'][] = $row;
  86. }
  87. /* Mode export */
  88. if($_['export'] == 'true'){
  89. if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
  90. $fieldsMapping = array();
  91. foreach (ContactExample::fields(false) as $key => $value)
  92. $fieldsMapping[$value['label']] = $key;
  93. $stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
  94. File::downloadStream($stream,'export-contacts-'.date('d-m-Y').'.xlsx');
  95. exit();
  96. }
  97. });
  98. //Ajout ou modification d'élément contact
  99. Action::register('example_contact_save',function(&$response){
  100. global $_,$myFirm,$myUser;
  101. User::check_access('example','edit');
  102. require_once(__DIR__.SLASH.'ContactExample.class.php');
  103. //Check champs dynamiques
  104. if($myFirm->has_plugin('fr.core.dynamicform')){
  105. Plugin::need('dynamicform/DynamicForm');
  106. $dynamicFields = Dynamicform::check_required('fiche-example',array(),$_);
  107. }
  108. $item = ContactExample::provide();
  109. //on garde l'ancien objet a l'instant t pour le log comparatif (voir en fin d'action)
  110. $oldItem = clone $item;
  111. $item->label = $_['label'];
  112. $item->phone = $_['phone'];
  113. $item->birth = timestamp_date($_['birth']);
  114. $item->hour = $_['hour'];
  115. $item->firm = $_['firm'];
  116. $item->manager = $_['manager'];
  117. $item->address = $_['address'];
  118. $item->properties = $_['properties'];
  119. if(!empty($_['vehicle']) ) $item->vehicle = $_['vehicle'];
  120. $item->storyshort = $_['storyshort'];
  121. $item->story = $_['story'];
  122. $item->password = $_['password'];
  123. $item->icon = $_['icon'];
  124. $item->available = $_['available'];
  125. $item->solvability = $_['solvability'];
  126. $item->handicap = (isset($_['handicap']) && !empty($_['handicap'])) ? value_encapsulate($_['handicap'], ',') : NULL;
  127. $item->childs = $_['childs'];
  128. if(is_numeric($_['size'])) $item->size = $_['size'];
  129. $item->color = $_['color'];
  130. $item->salary = $_['salary'];
  131. if(!empty($_['orientation'])) $item->orientation = $_['orientation'];
  132. $item->website = $_['website'];
  133. $item->mail = $_['mail'];
  134. $item->save();
  135. //save champs dynamiques
  136. if($myFirm->has_plugin('fr.core.dynamicform')){
  137. Dynamicform::record('fiche-example',array(
  138. 'scope'=>'contact',
  139. 'uid'=>$item->id,
  140. 'fields' => $dynamicFields
  141. ),$_);
  142. }
  143. //Ajout upload Cv
  144. if(!empty($_['cv']))
  145. File::save_component('cv', 'example/contact/'.$item->id.'/cv/{{label}}');
  146. //Ajout upload Avatar
  147. if(!empty($_['avatar']))
  148. File::save_component('avatar', 'example/contact/'.$item->id.'/avatar.{{extension}}');
  149. //Exemple de mise en place de logs comparatif
  150. History::entityChange('contact',$oldItem,$item);
  151. //trigger pour utilisation sur le workflow
  152. if($myFirm->has_plugin('fr.core.workflow')){
  153. Plugin::need('workflow/WorkflowEvent');
  154. WorkflowEvent::trigger('example-contact-'.($oldItem->id==0?'create':'update'),array('old'=>$oldItem,'current'=>$item));
  155. }
  156. // GESTION ENVOI NOTIFICATION
  157. Plugin::callHook('emit_notification',array(array(
  158. 'label' => isset($item->id) ? 'Édition d\'un contact' : 'Création d\'un contact',
  159. 'html' => isset($item->id) ? 'Le contact '.$item->label.' a été édité' : 'Création du contact '.$item->label,
  160. 'type' => "notice",
  161. 'meta' => array('link' => ROOT_URL.'/index.php?module=example&page=sheet&id='.$item->id),
  162. 'recipients' => array($myUser->login) // recipients contient login
  163. )
  164. ));
  165. $response = $item->toArray();
  166. });
  167. Action::register('contact_wysiwyg_attachments',function(&$response){
  168. $directory = File::dir().SLASH.'public'.SLASH.'example';
  169. User::check_access('example','read');
  170. global $_;
  171. if(!isset($_FILES['stream'])) throw new Exception("Fichier inexistant");
  172. if(!in_array($_FILES['stream']['type'], array('image/png','image/jpg','image/jpeg','image/gif','image/bmp','application/pdf'))) throw new Exception("Format du fichier non autorisé :".$_FILES['stream']['type']);
  173. $ext = mb_strtolower(getExt($_['name']));
  174. //Gère l'upload d'un fichier image collé dans le wysiwyg
  175. $pathes = File::upload('stream', 'example/public/screens/'.time().'.'.$ext, 1048576, null);
  176. if(preg_match('/^image\//', $_FILES['stream']['type'])){
  177. $response['html'] = '<img src="'.ROOT_URL.'/media/'.$pathes['relative'].'"/>';
  178. }else{
  179. $response['html'] = '<a href="'.ROOT_URL.'/media/'.$pathes['relative'].'">'.$_['name'].'</a>';
  180. }
  181. });
  182. //Suppression d'élement contact
  183. Action::register('example_contact_delete',function(&$response){
  184. global $myUser,$_,$myFirm;
  185. User::check_access('example','delete');
  186. require_once(__DIR__.SLASH.'ContactExample.class.php');
  187. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  188. ContactExample::deleteById($_['id']);
  189. //Gestion des champs dynamiques
  190. if($myFirm->has_plugin('fr.core.dynamicform')){
  191. Plugin::need('dynamicform/DynamicForm');
  192. Dynamicform::remove('fiche-example',array(
  193. 'scope'=>'contact',
  194. 'uid'=>$_['id']
  195. ));
  196. }
  197. });
  198. //ContactExample : Gestion upload Cv
  199. Action::register('example_contact_cv',function(&$response){
  200. File::handle_component(array(
  201. 'namespace' => 'example', //stockés dans file/example/*.*
  202. 'access' => 'example', // crud sur example,
  203. 'size' => '1000000000', // taille max
  204. 'storage' => 'example/contact/{{data.id}}/cv/*' //chemin complet vers le fichier stocké
  205. ),$response);
  206. });//ContactExample : Gestion upload Avatar
  207. Action::register('example_contact_avatar',function(&$response){
  208. File::handle_component(array(
  209. 'namespace' => 'example', //stockés dans file/example/*.*
  210. 'access' => 'example', // crud sur example,
  211. 'size' => '1000000000', // taille max
  212. 'limit' => '1', // nb max de fichiers
  213. 'storage' => 'example/contact/{{data.id}}/avatar.*' //chemin complet vers le fichier stocké
  214. ),$response);
  215. });
  216. /** QUICKFORM **/
  217. //Création rapide par quickform
  218. Action::register('contact_quick_create',function(&$response){
  219. global $myUser,$_;
  220. User::check_access('example','edit');
  221. require_once(__DIR__.SLASH.'ContactExample.class.php');
  222. ob_start();
  223. require_once(__DIR__.SLASH.'page.quick.example.php');
  224. $response['content'] = ob_get_clean();
  225. });
  226. /** CARD **/
  227. //Récupération card d'un contact
  228. Action::register('example_contact_card',function(&$response){
  229. global $myUser,$myFirm,$_;
  230. User::check_access('example','read');
  231. require_once(__DIR__.SLASH.'ContactExample.class.php');
  232. $contact = ContactExample::provide();
  233. ob_start();
  234. require_once(__DIR__.SLASH.'card.example.contact.php');
  235. $stream = ob_get_clean();
  236. $response['content'] = $stream;
  237. });
  238. Action::register('example_widget_load',function(&$response){
  239. Plugin::need('dashboard/DashboardWidget');
  240. User::check_access('example','read');
  241. $widget = DashboardWidget::current();
  242. $widget->title = 'Widget Example';
  243. ob_start();
  244. //Décommenter après avoir créé widget.php
  245. //require_once(__DIR__.SLASH.'widget.php');
  246. //$widget->content = ob_get_clean();
  247. $widget->content = 'Widget non développé';
  248. echo json_encode($widget);
  249. });
  250. //Sauvegarde des configurations de Example
  251. Action::register('example_setting_save',function(&$response){
  252. global $_,$conf;
  253. User::check_access('example','configure');
  254. //Si input file "multiple", possibilité de normaliser le
  255. //tableau $_FILES récupéré avec la fonction => normalize_php_files();
  256. foreach(Configuration::setting('example') as $key=>$value){
  257. if(!is_array($value)) continue;
  258. $allowed[] = $key;
  259. }
  260. foreach ($_['fields'] as $key => $value) {
  261. if(in_array($key, $allowed))
  262. $conf->put($key,$value);
  263. }
  264. });
  265. ?>