Odyssey
mFeatureMnu.data
1 <?php
2 /**
3  * mFeatureMnu.data
4  *
5  * This script will accept requests from the presentation and interact with the database
6  * for those requests. Some of those can be:
7  * Create
8  * Read
9  * Update
10  * Delete
11  *
12  * ** ERROR STATES **
13  * 900 - permissions failed for accessing this script
14  * 910 - Invalid API action encountered
15  * 950 - Transaction Failure
16  * 951 - Unable to delete row
17  * 952 - Unable to Relate Child to Parent
18  * 953 - Unable to Insert Row
19  * 954 - Unable to Commit Work
20  * 955 - Error Response when throwing from Exception to ErrorException
21  *
22  * MWS 10/24/2016
23  *
24  */
25 
26  /* *** FORM VARIABLES *** */
27  $homecuSharedLibrary = dirname(__FILE__) . "/../../shared/library";
28  $homecuMonitorLibrary = dirname(__FILE__) . "/../../monitor/library";
29 
30  $importValues = Array();
31 
32  /* *** */
33  try {
34 
35  /* ** PREVENT UNAUTHORIZED USE ** */
36  /* * Authenticate Session * */
37 
38  require_once("$homecuMonitorLibrary/cu_top.i");
39  require_once("$homecuMonitorLibrary/ck_hticket.i");
40  require_once("$homecuSharedLibrary/dms_imp_val.i");
41 
42  require_once("$homecuSharedLibrary/sFeatureMnu.i");
43 
44 /*
45  if (!CheckPerm($dbh, $Hu, basename($_SERVER['SCRIPT_NAME']), $_SERVER['REMOTE_ADDR'])) {
46  // ** Permissions failed
47  // ** this being a .data does not redirect
48 
49  throw new ErrorException ('Permissions Failed', '900');
50  }
51 */
52  /* * IMPORT VARIABLES * */
53  $importFieldAry = Array (
54  "cu" => array('filter' => FILTER_SANITIZE_STRING),
55  "api_action" => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('options' => array('regexp' => '/ignore|update|read|delete|settings/')))
56  );
57 /* OK TO REMOVE
58  * $input_array = array("col1"=>array('filter'=>FILTER_VALIDATE_INT),
59  * "col2"=>array('filter'=>FILTER_SANITIZE_FULL_SPECIAL_CHARS),
60  * "col3"=>array('filter'=>FILTER_VALIDATE_INT, 'flags'=>FILTER_REQUIRE_ARRAY),
61  * "col4"=>array('filter'=>FILTER_VALIDATE_REGEXP), 'options'=>array('regexp'=>'/[0-9]* /'))
62  *
63  * @return true - Always returns true
64  *
65  */
66  HCU_ImportVars($importValues, '', $importFieldAry);
67  switch ($importValues['api_action']) {
68  case 'settings':
69  /*
70  * RETURN form SETTINGS for:
71  * Menu Icons
72  * Feature List
73  * Platform Types
74  * Script Names
75  */
76  $retVal = Array("homecuData"=>Array());
77 
78  /* ** Get Menu Icons ** */
79  $iconListAry = GetFeatureMenuIcons();
80  $retVal['homecuData']['menuicons'] = ($iconListAry['code'] == '000' ? $iconListAry['data'] : Array());
81 
82  /* ** Get Menu Platforms ** */
83  $platformListAry = GetFeatureMenuPlatforms();
84  $retVal['homecuData']['menuplatforms'] = ($platformListAry['code'] == '000' ? $platformListAry['data'] : Array());
85 
86  /* ** Get Feature List ** */
87  $featureListAry = GetFeatureList($dbh);
88  $retVal['homecuData']['features'] = ($featureListAry['code'] == '000' ? $featureListAry['data'] : Array());
89 
90  /* ** Get Banking Screen ** */
91  $screenListAry = GetBankingScripts();
92  $retVal['homecuData']['scripts'] = ($screenListAry['code'] == '000' ? $screenListAry['data'] : Array());
93 
94  /* ** Get Available Languages ** */
95  $langListAry = GetSelectLang($dbh, $importValues['cu']);
96  // ** For this option default the English language to ON
97  $retVal['homecuData']['lang'] = ($langListAry['code'] == '000' ? $langListAry['data'] : Array("en_US" => true));
98  /* ** DATA COLLECTED ** */
99  /* ** RETURN RESULTS ** */
100  LocalPrintJson($retVal);
101 
102  break;
103  case 'read':
104  $menuList = Array(); // ** Menu List being built
105 
106  // ** Call the FetchFeatureMenu and return the results. This will return all platform types
107  $featureMenuResults = FetchFeatureMenu($dbh, $importValues['cu']);
108  if ($featureMenuResults['code'] == '000') {
109  if (count($featureMenuResults['data']) == 0) {
110  $featureMenuResults = FetchDefaultFeatureMenu($dbh, $importValues['cu']);
111  if ($featureMenuResults['code'] != '000') {
112  // Default Data Should be loaded - otherwise throw error
113  throw new ErrorException ("Unable to retrieve menu list");
114  }
115  }
116  } else {
117  // Default Data Should be loaded - otherwise throw error
118  throw new ErrorException ("Unable to retrieve menu list");
119 
120  }
121 
122 
123  if (is_array($featureMenuResults['data'])) {
124  $dataStoreMenu = $featureMenuResults['data']; // Menu as returned from the database or default template
125 
126 
127  $gridOrder = 0; // ** Grid Order value
128  $lastParentId = null; // Last Parent Group ID
129  $lastItemType = ''; // ** Menu Item Type of the last Parent Group
130  for ($menuIdx = 0; $menuIdx < count($dataStoreMenu); $menuIdx++) {
131  // ** loop through the array and at the end of a "parent" group add a "add item link"
132  $itemType = HCU_array_key_value('MenuItemType', $dataStoreMenu[$menuIdx]);
133  $menuItemId = HCU_array_key_value('MenuItemId', $dataStoreMenu[$menuIdx]);
134  // For new groups we may need to add a previous "Add Item" record
135  if ( $itemType != 'D' && $lastParentId !== $menuItemId ) {
136  // ** Different Group -- Do we need to record an 'Add Item' record
137  if ($lastItemType == 'H') {
138  // ** ** ADD ITEM ** **
139  $menuList[] = LocalAddItem($gridOrder++, -9999, $lastParentId);
140  }
141 
142  // ** SET THE NEW VALUES
143  $lastParentId = $menuItemId;
144  $lastItemType = $itemType;
145  }
146 
147  // ** ** ADD THE MENU ITEM ** **
148  $newMenuItem = $dataStoreMenu[$menuIdx];
149  // ** Need to add Grid Order
150  $newMenuItem['GridOrder'] = $gridOrder++;
151  $menuList[] = $newMenuItem;
152  }
153  // ** After we're done
154  // ** Do we add a new Group "add item"?
155  if ($lastItemType == 'H') {
156  // ** ** ADD ITEM ** **
157  $menuList[] = LocalAddItem($gridOrder++, -9999, $lastParentId);
158  }
159  // ** ALWAYS ADD A add Menu group Item
160  $menuList[] = LocalAddItem($gridOrder, -9999, null);
161  }
162 
163 
164  $retVal['homecuData']['featuremenu'] = $menuList;
165 
166 
167  /* ** DATA COLLECTED ** */
168  /* ** RETURN RESULTS ** */
169  LocalPrintJson($retVal);
170 
171  break;
172  case 'update':
173 
174  /*
175  * Update Rules
176  *
177  * Structure of the update should have 4 elements
178  * cu - CU Code
179  * api_action - What is being done (update)
180  * data - consists of
181  * deleted - json string deleted rows
182  * updated - json string of updated rows
183  *
184  * *** NOTE:: ****
185  * Because I want to handle both updated and deleted at the same time, I am sending over the data
186  * in a less traditional manner The objects are being converted to json string and being sent as
187  * data_deleted
188  * data_udpated
189  *
190  * This is import as I will need to decode these values and json decode them before I can use them
191  */
192  try {
193  $retVal = Array("homecuData"=>Array());
194 
195  $updateValues = Array();
196  $importFieldAry = Array (
197  "data_deleted" => array('filter' => FILTER_SANITIZE_STRING),
198  "data_updated" => array('filter' => FILTER_SANITIZE_STRING)
199  );
200  HCU_ImportVars($updateValues, '', $importFieldAry);
201 
202  $recCountDel = 0;
203  $recCountUpd = 0;
204  $recCountIns = 0;
205 
206 
207  $delRecords = HCU_JsonDecode(html_entity_decode($updateValues['data_deleted']));
208 
209  $updRecords = HCU_JsonDecode(html_entity_decode($updateValues['data_updated']));
210 
211 
212  /* **** START TRANSACTION / WORK **** */
213  if (!db_work($dbh, HOMECU_WORK_BEGIN)) {
214  // ** This should bypass the first try/catch is it is only catching Exception
215  throw new ErrorException ('Could not start transaction', 950);
216  }
217 
218 
219  /* **** DELETE RECORDS **** */
220  if (count($delRecords) > 0) {
221 
222  // ** Loop through each record and record them
223  for ($delIdx = 0; $delIdx < count($delRecords); $delIdx++) {
224 
225  if (HCU_array_key_exists("MenuItemId", $delRecords[$delIdx])) {
226  // ** Found the MenuItemId in the row
227  // ** make sure it is > 0
228  $delMenuId = intval(HCU_array_key_value("MenuItemId", $delRecords[$delIdx]));
229  if ($delMenuId > 0) {
230  $recordValues = Array(
231  'cu' => $importValues['cu'],
232  'menu_item_id' => $delMenuId
233  ); /// ** SET RECORD VALUES FOR DELETE
234 
235  // ** This appears to be a valid record ID.. Delete it
236  $updDel = FeatureMenuDeleteItem($dbh, $recordValues);
237  $recCountDel++;
238  if (!$updDel) {
239  throw new Exception ('Unable to delete MenuItemId ' . $delMenuId, 951);
240  }
241 
242  }
243  }
244 
245  }
246  }
247 
248  /* **** PASS ONE **** */
249  /* *** ORDER ARRAY by GridOrder *** */
250  usort($updRecords, function ($item1, $item2) {
251  // ** This should order the results in order of GridOrder. (PHP 7 COMPAT ONLY)
252  //** This should help maintain the order as new menu group/items are
253  // ** added and the MenuItemId needs to be recorded
254  return $item1['GridOrder'] <=> $item2['GridOrder'];
255 
256  });
257 
258 
259  /* **** PASS TWO **** */
260  /* *** LOOP THROUGH ARRAY *** */
261  $newParentIdLookup = Array(); // ** Array for looking up the New Parent ID Sequence number
262  $platformList = Array("D" => "dsk", "M" => "mbl", "A" => "app");
263  $cuLangOptions = GetSelectLang($dbh, $importValues['cu']);
264  $langList = $cuLangOptions['data'];
265 
266  if (count($updRecords) > 0) {
267  // * Update Records found
268  for ($recIdx = 0; $recIdx < count($updRecords); $recIdx++) {
269  if (HCU_array_key_exists("MenuItemId", $updRecords[$recIdx])) {
270  $curRecord = $updRecords[$recIdx];
271  /**
272  * Do not update any MenuItemId with value -9999
273  * // These are record holders for new rows
274  *
275  *
276  *
277  */
278  $menuId = HCU_array_key_value("MenuItemId", $curRecord);
279  $parentId = HCU_array_key_value("ParentId", $curRecord);
280 
281  if ($menuId != -9999) {
282  // ** Record the Current Payment Group
283  $recordValues = Array(); /// ** RESET RECORD VALUES
284 
285  /* *** SET RECORD VALUES *** */
286  // ** The data being returned is not compatible with the database
287  // ** Need to evaluate the data being sent and convert into the record columns
288 
289  /**
290  * Notes on updating parent/child relationship
291  * It is required that the parent child relationship must be in the order of Parent then Child
292  * When a NEW Group is saved, it will record it's Old Parent ID, newParentId in an array
293  * * any children that reference the old Parent ID, will change to the new Parent ID
294  */
295  /*
296  * ** COLUMNS
297  * ** ** menu_item_id
298  * ** ** cu
299  * ** ** display_order
300  * ** ** feature_code
301  * ** ** parent_item_id
302  * ** ** menu_item_type
303  * ** ** menu_item_platform
304  * ** ** menu_item_attr
305  */
306  /* ** menu_item_id ** */
307  if ($menuId < 0) {
308  $recordValues['menu_item_id'] = 'nextval'; // This will trigger the next function to use a SERIAL VALUES
309  } else {
310  $recordValues['menu_item_id'] = $menuId;
311  }
312 
313  /* ** cu ** */
314  $recordValues['cu'] = $importValues['cu'];
315 
316  /* ** display_order ** */
317  $recordValues['display_order'] = intval(HCU_array_key_value('DisplayOrder', $curRecord));
318 
319  /* ** menu_item_type ** */
320  $recordValues['menu_item_type'] = HCU_array_key_value('MenuItemType', $curRecord);
321 
322  /* ** feature_code ** */
323  $recordValues['feature_code'] = HCU_array_key_value('FeatureCode', $curRecord);
324 
325  /* ** parent_item_id ** */
326  if ($recordValues['menu_item_type'] == 'D') {
327  /* * CHILD MENU ITEM */
328  $tempParentId = intval(HCU_array_key_value('ParentId', $curRecord));
329  if ($tempParentId < 0) {
330  // ** Need to lookup in the parent lookup list
331  if (HCU_array_key_exists($tempParentId, $newParentIdLookup)) {
332  $tempParentId = HCU_array_key_value($tempParentId, $newParentIdLookup);
333  } else {
334  // ** SOMETHING IS WRONG !!! -- There should have been a value -- FOR NOW EXIST
335  throw new Exception ('Unable to relate child to parent', 952);
336  }
337  } // else child already has correct parent id
338  } else {
339  /* * HEADER / STANDALONE MENU LINK * */
340  /* ALWAYS NULL */
341  $recordValues['parent_item_id'] = 'null';
342  $tempParentId = 'null';
343  }
344  $recordValues['parent_item_id'] = $tempParentId;
345 
346  /* ** menu_item_platform ** */
347  // ** Build from details_platform_dsk, details_platform_mbl, details_platform_app
348  $tempMenuPlatform = Array();
349  reset($platformList);
350  foreach ($platformList as $platKey => $platField) {
351  $platFieldName = 'details_platform_' . $platField;
352  if (HCU_array_key_exists($platFieldName, $curRecord)) {
353  // ** Add if true
354  if (HCU_array_key_value($platFieldName, $curRecord)) {
355  $tempMenuPlatform[] = $platKey;
356  }
357  }
358  }
359 
360  $recordValues['menu_item_platform'] = HCU_JsonEncode($tempMenuPlatform);
361 
362  /* ** menu_item_attr ** */
363  $tempMenuAttr = Array();
364 
365  /* ** Made up of the following; ** */
366 
367  /* * display * */
368  $tempLang = Array();
369  foreach ($langList as $langKey => $langVal) {
370  // ** Currently langVal is {true/false}, only evaluate if true
371  if ($langVal) {
372  $tempLang[$langKey] = HCU_array_key_value('details_display_' . $langKey, $curRecord);
373  }
374  }
375  $tempMenuAttr['display'] = $tempLang;
376 
377  /* * fa-icon * */
378  // ** ONLY FOR HEADER / MENU LEVEL LINKS (NO CHILDREN)
379  $tempIcon = '';
380  if ($recordValues['menu_item_type'] != 'D') {
381  $tempIcon = HCU_array_key_value('details_fa_icon', $curRecord);
382  }
383  $tempMenuAttr['fa-icon'] = $tempIcon;
384  $tempMenuAttr['collapseGroup'] = (HCU_array_key_value('details_collapse_group', $curRecord) == 1 ? 1 : 0);
385 
386  $tempMenuAttr["memAcctFilter"]= HCU_array_key_exists("details_memacct_filter", $curRecord) ? $curRecord["details_memacct_filter"] : "";
387 
388  /* *** THE FOLLOWING DO NOT APPLY TO HEADER *** */
389  if ($recordValues['menu_item_type'] != 'H') {
390  /* * href * */
391  $tempMenuAttr['href'] = HCU_array_key_value('details_href', $curRecord);
392 
393  /* * hrefUrlQuery * */
394  $tempMenuAttr['hrefUrlQuery'] = (HCU_array_key_value('details_hrefUrlQuery', $curRecord) == 1 ? 1 : 0);
395 
396  /* * target * */
397  $tempMenuAttr['target'] = (HCU_array_key_value('details_target', $curRecord) == 1 ? 1 : 0);
398 
399  /* * message * */
400  $tempMenuAttr['externalMsg'] = (HCU_array_key_value('details_message', $curRecord) == 1 ? 1 : 0);
401 
402  /* * hrefExtraParam * */
403  $tempMenuAttr['hrefExtraParam'] = HCU_array_key_value('details_hrefExtraParam', $curRecord);
404  }
405  /* ** menu_item_attr ** */
406  $recordValues['menu_item_attr'] = HCU_JsonEncode($tempMenuAttr);
407 
408  // ** recordValues should now contain the updated values -- This will be passed to the appropriate function
409 
410  /* *** INSERT / UPDATE RECORD *** */
411 
412  $insertRow = FeatureMenuUpdateItem($dbh, ($menuId < 0 ? "INSERT" : "UPDATE"), $recordValues);
413  if ($insertRow === false) {
414  throw new Exception ('Unable to insert Menu Item', 953);
415  }
416  // ** insertRow will be the information returned, which will include the new menu_item_id column
417  $tempMenuId = intval(HCU_array_key_value('menu_item_id', $insertRow));
418 
419 
420  // * Create a lookup so we can translate the old id to new id
421  // ** INSERTED ITEMS ONLY
422  // ** This can be used by clien to update the screen
423  if ($menuId < 0) {
424  $newParentIdLookup[$menuId] = $tempMenuId;
425  $recCountIns++;
426  } else {
427  $recCountUpd++;
428  }
429 
430  }
431  }
432  }
433  }
434 
435  /* ALL TRANSACTIONS ARE POSTED */
436  /* **** COMMIT **** */
437 
438  if (db_work($dbh, HOMECU_WORK_COMMIT)) {
439  $status = Array();
440  $status[] = "Menu Updated";
441  if ($recCountDel > 0) {
442  $status[] = "$recCountDel Item(s) Deleted";
443  }
444  if ($recCountIns > 0) {
445  $status[] = "$recCountIns Item(s) Inserted";
446  }
447  if ($recCountUpd > 0) {
448  $status[] = "$recCountUpd Item(s) Updated";
449  }
450  $retVal['homecuData']['status'] = $status;
451 
452  $retVal['homecuData']['featuresave']['updateId'] = $newParentIdLookup;
453 
454  LocalPrintJson($retVal); // Return success
455  } else {
456  throw new Exception ('Unable to commit!', 954);
457  }
458 
459  /* **** END TRANSACTION / WORK **** */
460  } catch (Exception $errWork) {
461  // ** I want to trap Errors to the commit process separately
462  // * If something goes wrong be sure to rollback
463  $rollbackWork = db_work($dbh, HOMECU_WORK_ROLLBACK);
464  throw new ErrorException ("Error during update!", 955);
465  }
466  break;
467  case 'ignore':
468  // ** Ignore this request ** //
469  $retVal['homecuData']['featureignore'] = true;
470  LocalPrintJson($retVal); // Return success
471 
472  break;
473  default:
474  /* INVALID API ACTION */
475  throw new ErrorException ('Invalid API Action', 910);
476  }
477 
478 
479 
480  } catch ( Error $e) {
481 
482 
483 
484  } catch (ErrorException $e) {
485 
486  // ** All else fails
487  $retVal['homecuData'] = Array(); // Zero out any information already in the array
488  $retVal['homecuErrors'] = Array($e->getMessage());
489 
490  LocalPrintJson($retVal);
491  }
492 
493  /**
494  * This will take the return array, json encode it, and print to stream and exit script
495  *
496  * @param array $jsonDataArray homecu array to be printed
497  *
498  * @return none
499  */
500  function LocalPrintJson($jsonDataArray) {
501 
502  header('Content-type: application/json');
503 
504  print HCU_JsonEncode(Array("Results" => Array($jsonDataArray)));
505  exit;
506  }
507 
508  /**
509  * Returns a MenuItem row that is used to add a new menu item
510  *
511  * @param integer $pGridOrder - Grid order to be assigned
512  * @param integer $pMenuItemId - The Menu Item Id to assign
513  * @param mixed $pParentId - the parent id , this can be an integer for detail or null for adding menu group
514  */
515  function LocalAddItem($pGridOrder, $pMenuItemId, $pParentId) {
516 
517  return Array('GridOrder' => $pGridOrder, 'MenuItemId' => $pMenuItemId, 'ParentId' => $pParentId);
518 
519  }