]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/ModuleBuilder/parsers/views/GridLayoutMetaDataParser.php
Release 6.2.3
[Github/sugarcrm.git] / modules / ModuleBuilder / parsers / views / GridLayoutMetaDataParser.php
1 <?php
2 if (! defined ( 'sugarEntry' ) || ! sugarEntry)
3     die ( 'Not A Valid Entry Point' ) ;
4 /*********************************************************************************
5  * SugarCRM Community Edition is a customer relationship management program developed by
6  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7  * 
8  * This program is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Affero General Public License version 3 as published by the
10  * Free Software Foundation with the addition of the following permission added
11  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
12  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
13  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14  * 
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
18  * details.
19  * 
20  * You should have received a copy of the GNU Affero General Public License along with
21  * this program; if not, see http://www.gnu.org/licenses or write to the Free
22  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23  * 02110-1301 USA.
24  * 
25  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
26  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27  * 
28  * The interactive user interfaces in modified source and object code versions
29  * of this program must display Appropriate Legal Notices, as required under
30  * Section 5 of the GNU Affero General Public License version 3.
31  * 
32  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
33  * these Appropriate Legal Notices must retain the display of the "Powered by
34  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
35  * technical reasons, the Appropriate Legal Notices must display the words
36  * "Powered by SugarCRM".
37  ********************************************************************************/
38
39
40 require_once 'modules/ModuleBuilder/parsers/views/AbstractMetaDataParser.php' ;
41 require_once 'modules/ModuleBuilder/parsers/views/MetaDataParserInterface.php' ;
42 require_once 'modules/ModuleBuilder/parsers/constants.php' ;
43
44 class GridLayoutMetaDataParser extends AbstractMetaDataParser implements MetaDataParserInterface
45 {
46
47     static $variableMap = array (
48         MB_EDITVIEW => 'EditView' ,
49         MB_DETAILVIEW => 'DetailView' ,
50         MB_QUICKCREATE => 'QuickCreate',
51         ) ;
52
53         protected $FILLER ;
54
55     /*
56      * Constructor
57      * @param string view           The view type, that is, editview, searchview etc
58      * @param string moduleName     The name of the module to which this view belongs
59      * @param string packageName    If not empty, the name of the package to which this view belongs
60      */
61     function __construct ($view , $moduleName , $packageName = '')
62     {
63         $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->__construct( {$view} , {$moduleName} , {$packageName} )" ) ;
64
65         $view = strtolower ( $view ) ;
66
67         // BEGIN ASSERTIONS
68         if (! isset ( self::$variableMap [ $view ] ) )
69             sugar_die ( get_class ( $this ) . ": View $view is not supported" ) ;
70         // END ASSERTIONS
71
72                 $this->FILLER = array ( 'name' => MBConstants::$FILLER['name'] , 'label' => translate ( MBConstants::$FILLER['label'] ) ) ;
73
74         $this->_moduleName = $moduleName ;
75         $this->_view = $view ;
76
77         if (empty ( $packageName ))
78         {
79             require_once 'modules/ModuleBuilder/parsers/views/DeployedMetaDataImplementation.php' ;
80             $this->implementation = new DeployedMetaDataImplementation ( $view, $moduleName, self::$variableMap ) ;
81         } else
82         {
83             require_once 'modules/ModuleBuilder/parsers/views/UndeployedMetaDataImplementation.php' ;
84             $this->implementation = new UndeployedMetaDataImplementation ( $view, $moduleName, $packageName ) ;
85         }
86
87         $viewdefs = $this->implementation->getViewdefs () ;
88
89         if (! isset ( $viewdefs [ self::$variableMap [ $view ] ] ))
90             sugar_die ( get_class ( $this ) . ": missing variable " . self::$variableMap [ $view ] . " in layout definition" ) ;
91
92         $viewdefs = $viewdefs [ self::$variableMap [ $view ] ] ;
93         if (! isset ( $viewdefs [ 'templateMeta' ] ))
94             sugar_die ( get_class ( $this ) . ": missing templateMeta section in layout definition (case sensitive)" ) ;
95
96         if (! isset ( $viewdefs [ 'panels' ] ))
97             sugar_die ( get_class ( $this ) . ": missing panels section in layout definition (case sensitive)" ) ;
98
99         $this->_viewdefs = $viewdefs ;
100         if ($this->getMaxColumns () < 1)
101             sugar_die ( get_class ( $this ) . ": maxColumns=" . $this->getMaxColumns () . " - must be greater than 0!" ) ;
102
103         $this->_fielddefs =  $this->implementation->getFielddefs() ;
104         $this->_standardizeFieldLabels( $this->_fielddefs );
105         $this->_viewdefs [ 'panels' ] = $this->_convertFromCanonicalForm ( $this->_viewdefs [ 'panels' ] , $this->_fielddefs ) ; // put into our internal format
106         $this->_originalViewDef = $this->getFieldsFromLayout($this->implementation->getOriginalViewdefs ());
107     }
108
109     /*
110      * Save a draft layout
111      */
112     function writeWorkingFile ($populate = true)
113     {
114         if ($populate)
115             $this->_populateFromRequest ( $this->_fielddefs ) ;
116         
117         $viewdefs = $this->_viewdefs ;
118         $viewdefs [ 'panels' ] = $this->_convertToCanonicalForm ( $this->_viewdefs [ 'panels' ] , $this->_fielddefs ) ;
119         $this->implementation->save ( array ( self::$variableMap [ $this->_view ] => $viewdefs ) ) ;
120     }
121
122     /*
123      * Deploy the layout
124      * @param boolean $populate If true (default), then update the layout first with new layout information from the $_REQUEST array
125      */
126     function handleSave ($populate = true)
127     {
128         $GLOBALS [ 'log' ]->info ( get_class ( $this ) . "->handleSave()" ) ;
129
130         if ($populate)
131             $this->_populateFromRequest ( $this->_fielddefs ) ;
132
133         $viewdefs = $this->_viewdefs ;
134         $viewdefs [ 'panels' ] = $this->_convertToCanonicalForm ( $this->_viewdefs [ 'panels' ] , $this->_fielddefs ) ;
135         $this->implementation->deploy ( array ( self::$variableMap [ $this->_view ] => $viewdefs ) ) ;
136     }
137
138     /*
139      * Return the layout, padded out with (empty) and (filler) fields ready for display
140      */
141     function getLayout ()
142     {
143         $viewdefs = array () ;
144         $fielddefs = $this->_fielddefs;
145         $fielddefs [ $this->FILLER [ 'name' ] ] = $this->FILLER ;
146         $fielddefs [ MBConstants::$EMPTY [ 'name' ] ] = MBConstants::$EMPTY ;
147         
148                 foreach ( $this->_viewdefs [ 'panels' ] as $panelID => $panel )
149         {
150             foreach ( $panel as $rowID => $row )
151             {
152                 foreach ( $row as $colID => $fieldname )
153                 {
154                         if (isset ($this->_fielddefs [ $fieldname ]))
155                                         {
156                                                 $viewdefs [ $panelID ] [ $rowID ] [ $colID ] = self::_trimFieldDefs( $this->_fielddefs [ $fieldname ] ) ;
157                                         } 
158                                         else if (isset($this->_originalViewDef [ $fieldname ]) && is_array($this->_originalViewDef [ $fieldname ]))
159                                         {
160                                                 $viewdefs [ $panelID ] [ $rowID ] [ $colID ] = self::_trimFieldDefs( $this->_originalViewDef [ $fieldname ] ) ;
161                                         } 
162                                         else 
163                                         {
164                                                 $viewdefs [ $panelID ] [ $rowID ] [ $colID ] = array("name" => $fieldname, "label" => $fieldname);
165                                         }
166                 }
167             }
168         }
169         return $viewdefs ;
170     }
171
172     function getMaxColumns ()
173     {
174         if (!empty( $this->_viewdefs) && isset($this->_viewdefs [ 'templateMeta' ] [ 'maxColumns' ]))
175                 {
176                         return $this->_viewdefs [ 'templateMeta' ] [ 'maxColumns' ] ;
177                 }else
178                 {
179                         return 2;
180                 }
181     }
182
183     function getAvailableFields ()
184     {
185
186         // Obtain the full list of valid fields in this module
187         $availableFields = array () ;
188         foreach ( $this->_fielddefs as $key => $def )
189         {
190             if ( GridLayoutMetaDataParser::validField ( $def,  $this->_view ) || isset($this->_originalViewDef[$key]) )
191             {
192                 //If the field original label existing, we should use the original label instead the label in its fielddefs.
193                 if(isset($this->_originalViewDef[$key]) && is_array($this->_originalViewDef[$key]) && isset($this->_originalViewDef[$key]['label'])){
194                     $availableFields [ $key ] = array ( 'name' => $key , 'label' => $this->_originalViewDef[$key]['label']) ; 
195                 }else{
196                     $availableFields [ $key ] = array ( 'name' => $key , 'label' => isset($def [ 'label' ]) ? $def [ 'label' ] : $def['vname'] ) ; // layouts use 'label' not 'vname' for the label entry
197                 }
198                 $availableFields[$key]['translatedLabel'] = translate($def['label'], $this->_moduleName);
199             }
200                         
201         }
202
203                 // Available fields are those that are in the Model and the original layout definition, but not already shown in the View
204         // So, because the formats of the two are different we brute force loop through View and unset the fields we find in a copy of Model
205         if (! empty ( $this->_viewdefs ))
206         {
207             foreach ( $this->_viewdefs [ 'panels' ] as $panel )
208             {
209                 foreach ( $panel as $row )
210                 {
211                     foreach ( $row as $field )
212                     {
213                         unset ( $availableFields [ $field ] ) ;
214                     }
215                 }
216             }
217         }
218         
219         //eggsurplus: Bug 10329 - sort on intuitive display labels
220         //sort by translatedLabel
221         function cmpLabel($a, $b) 
222         {
223             return strcmp($a["translatedLabel"], $b["translatedLabel"]);
224         }
225         usort($availableFields , 'cmpLabel');
226
227         return $availableFields ;
228     }
229
230     function getPanelDependency ( $panelID )
231     {
232         if ( ! isset ( $this->_viewdefs [ 'templateMeta' ][ 'dependency' ] ) && ! isset ( $this->_viewdefs [ 'templateMeta' ][ 'dependency' ] [ $panelID ] ) )
233                 return false;
234
235         return $this->_viewdefs  [ 'templateMeta' ][ 'dependency' ] [ $panelID ] ;
236     }
237
238     /*
239      * Add a new field to the layout
240      * If $panelID is passed in, attempt to add to that panel, otherwise add to the first panel
241      * The field is added in place of the first empty (not filler) slot after the last field in the panel; if that row is full, then a new row will be added to the end of the panel
242      * and the field added to the start of it.
243      * @param array $def Set of properties for the field, in same format as in the viewdefs
244      * @param string $panelID Identifier of the panel to add the field to; empty or false if we should use the first panel
245      */
246     function addField ( $def , $panelID = FALSE)
247     {
248
249         if (count ( $this->_viewdefs [ 'panels' ] ) == 0)
250         {
251             $GLOBALS [ 'log' ]->error ( get_class ( $this ) . "->addField(): _viewdefs empty for module {$this->_moduleName} and view {$this->_view}" ) ;
252         }
253
254         // if a panelID was not provided, use the first available panel in the list
255         if (! $panelID)
256         {
257             $panels = array_keys ( $this->_viewdefs [ 'panels' ] ) ;
258             list ( $dummy, $panelID ) = each ( $panels ) ;
259         }
260
261         if (isset ( $this->_viewdefs [ 'panels' ] [ $panelID ] ))
262         {
263
264             $panel = $this->_viewdefs [ 'panels' ] [ $panelID ] ;
265             $lastrow = count ( $panel ) - 1 ; // index starts at 0
266             $maxColumns = $this->getMaxColumns () ;
267             $lastRowDef = $this->_viewdefs [ 'panels' ] [ $panelID ] [ $lastrow ];
268             for ( $column = 0 ; $column < $maxColumns ; $column ++ )
269             {
270                 if (! isset ( $lastRowDef [ $column ] )
271                         || (is_array( $lastRowDef [ $column ]) && $lastRowDef [ $column ][ 'name' ] == '(empty)')
272                         || (is_string( $lastRowDef [ $column ]) && $lastRowDef [ $column ] == '(empty)')
273                 ){
274                     break ;
275                 }
276             }
277
278             // if we're on the last column of the last row, start a new row
279             if ($column >= $maxColumns)
280             {
281                 $lastrow ++ ;
282                 $this->_viewdefs [ 'panels' ] [ $panelID ] [ $lastrow ] = array ( ) ;
283                 $column = 0 ;
284             }
285
286             $this->_viewdefs [ 'panels' ] [ $panelID ] [ $lastrow ] [ $column ] = $def [ 'name' ] ;
287             // now update the fielddefs
288             if (isset($this->_fielddefs [ $def [ 'name' ] ]))
289             {
290                 $this->_fielddefs [ $def [ 'name' ] ] = array_merge ( $this->_fielddefs [ $def [ 'name' ] ] , $def ) ;
291             } else
292             {
293                 $this->_fielddefs [ $def [ 'name' ] ] = $def;
294             }
295         }
296         return true ;
297     }
298
299     /*
300      * Remove all instances of a field from the layout, and replace by (filler)
301      * Filler because we attempt to preserve the customized layout as much as possible - replacing by (empty) would mean that the positions or sizes of adjacent fields may change
302      * If the last row of a panel only consists of (filler) after removing the fields, then remove the row also. This undoes the standard addField() scenario;
303      * If the fields had been moved around in the layout however then this will not completely undo any addField()
304      * @param string $fieldName Name of the field to remove
305      * @return boolean True if the field was removed; false otherwise
306      */
307     function removeField ($fieldName)
308     {
309         $GLOBALS [ 'log' ]->info ( get_class ( $this ) . "->removeField($fieldName)" ) ;
310
311         $result = false ;
312         reset ( $this->_viewdefs ) ;
313         $firstPanel = each ( $this->_viewdefs [ 'panels' ] ) ;
314         $firstPanelID = $firstPanel [ 'key' ] ;
315
316         foreach ( $this->_viewdefs [ 'panels' ] as $panelID => $panel )
317         {
318             $lastRowTouched = false ;
319             $lastRowID = count ( $this->_viewdefs [ 'panels' ] [ $panelID ] ) - 1 ; // zero offset
320
321             foreach ( $panel as $rowID => $row )
322             {
323
324                 foreach ( $row as $colID => $field )
325                     if ($field == $fieldName)
326                     {
327                         $lastRowTouched = $rowID ;
328                         $this->_viewdefs [ 'panels' ] [ $panelID ] [ $rowID ] [ $colID ] = $this->FILLER [ 'name' ];
329                     }
330
331             }
332
333             // if we removed a field from the last row of this panel, tidy up if the last row now consists only of (empty) or (filler)
334
335             if ( $lastRowTouched ==  $lastRowID )
336             {
337                 $lastRow = $this->_viewdefs [ 'panels' ] [ $panelID ] [ $lastRowID ] ; // can't use 'end' for this as we need the key as well as the value...
338
339                 $empty = true ;
340
341                 foreach ( $lastRow as $colID => $field )
342                     $empty &=  $field == MBConstants::$EMPTY ['name' ] || $field == $this->FILLER [ 'name' ]  ;
343
344                 if ($empty)
345                 {
346                     unset ( $this->_viewdefs [ 'panels' ] [ $panelID ] [ $lastRowID ] ) ;
347                     // if the row was the only one in the panel, and the panel is not the first (default) panel, then remove the panel also
348                                         if ( count ( $this->_viewdefs [ 'panels' ] [ $panelID ] ) == 0 && $panelID != $firstPanelID )
349                                                 unset ( $this->_viewdefs [ 'panels' ] [ $panelID ] ) ;
350                 }
351
352             }
353
354             $result |= ($lastRowTouched !== false ); // explicitly compare to false as row 0 will otherwise evaluate as false
355         }
356
357         return $result ;
358
359     }
360
361     function setPanelDependency ( $panelID , $dependency )
362     {
363         // only accept dependencies for pre-existing panels
364         if ( ! isset ( $this->_viewdefs [ 'panels' ] [ $panelID ] ) )
365                 return false;
366
367         $this->_viewdefs  [ 'templateMeta' ] [ 'dependency' ] [ $panelID ] = $dependency ;
368         return true ;
369     }
370
371     /*
372      * Return an integer value for the next unused panel identifier, such that it and any larger numbers are guaranteed to be unused already in the layout
373      * Necessary when adding new panels to a layout
374      * @return integer First unique panel ID suffix
375      */
376     function getFirstNewPanelId ()
377     {
378         $firstNewPanelId = 0 ;
379         foreach ( $this->_viewdefs [ 'panels' ] as $panelID => $panel )
380         {
381             // strip out all but the numerics from the panelID - can't just use a cast as numbers may not be first in the string
382             for ( $i = 0, $result = '' ; $i < strlen ( $panelID ) ; $i ++ )
383             {
384                 if (is_numeric ( $panelID [ $i ] ))
385                 {
386                     $result .= $panelID [ $i ] ;
387                 }
388             }
389
390             $firstNewPanelId = max ( ( int ) $result, $firstNewPanelId ) ;
391         }
392         return $firstNewPanelId + 1 ;
393     }
394
395     /*
396      * Load the panel layout from the submitted form and update the _viewdefs
397      */
398     protected function _populateFromRequest ( &$fielddefs )
399     {
400         $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->populateFromRequest()" ) ;
401         $i = 1 ;
402
403         // set up the map of panel# (as provided in the _REQUEST) to panel ID (as used in $this->_viewdefs['panels'])
404         $i = 1 ;
405         foreach ( $this->_viewdefs [ 'panels' ] as $panelID => $panel )
406         {
407             $panelMap [ $i ++ ] = $panelID ;
408         }
409
410         foreach ( $_REQUEST as $key => $displayLabel )
411         {
412             $components = explode ( '-', $key ) ;
413             if ($components [ 0 ] == 'panel' && $components [ 2 ] == 'label')
414             {
415                 $panelMap [ $components [ '1' ] ] = $displayLabel ;
416             }
417         }
418
419         $this->_viewdefs [ 'panels' ] = array () ; // because the new field properties should replace the old fields, not be merged
420
421         // run through the $_REQUEST twice - first to obtain the fieldnames, the second to update the field properties
422         for ( $pass=1 ; $pass<=2 ; $pass++ )
423         {
424                 foreach ( $_REQUEST as $slot => $value )
425                 {
426                 $slotComponents = explode ( '-', $slot ) ; // [0] = 'slot', [1] = panel #, [2] = slot #, [3] = property name
427
428                 if ($slotComponents [ 0 ] == 'slot')
429                 {
430                         $slotNumber = $slotComponents [ '2' ] ;
431                         $panelID = $panelMap [ $slotComponents [ '1' ] ] ;
432                         $rowID = floor ( $slotNumber / $this->getMaxColumns () ) ;
433                         $colID = $slotNumber - ($rowID * $this->getMaxColumns ()) ;
434                         $property = $slotComponents [ '3' ] ;
435
436                         //If this field has a custom definition, copy that over
437                         if ( $pass == 1 )
438                         {
439                                 if ( $property == 'name' )
440                                 $this->_viewdefs [ 'panels' ] [ $panelID ] [ $rowID ] [ $colID ] = $value ;
441                         } else
442                         {
443                                 // update fielddefs for this property in the provided position
444                                 if ( isset ( $this->_viewdefs [ 'panels' ] [ $panelID ] [ $rowID ] [ $colID ] ) )
445                                 {
446                                         $fieldname = $this->_viewdefs [ 'panels' ] [ $panelID ] [ $rowID ] [ $colID ] ;
447                                                         $fielddefs [ $fieldname ] [ $property ] = $value ;
448                                 }
449                         }
450                 }
451
452                 }
453         }
454         
455         //Set the tabs setting
456         if (isset($_REQUEST['panels_as_tabs']))
457         {
458                 if ($_REQUEST['panels_as_tabs'] == false || $_REQUEST['panels_as_tabs'] == "false")
459                    $this->setUseTabs( false );
460                 else
461                    $this->setUseTabs( true );
462         }
463         
464         //bug: 38232 - Set the sync detail and editview settings
465         if (isset($_REQUEST['sync_detail_and_edit']))
466         {
467                 if ($_REQUEST['sync_detail_and_edit'] === false || $_REQUEST['sync_detail_and_edit'] === "false")
468             {
469                    $this->setSyncDetailEditViews( false );
470             }
471             elseif(!empty($_REQUEST['sync_detail_and_edit']))
472             {
473                    $this->setSyncDetailEditViews( true );
474             }
475         }
476
477         $GLOBALS [ 'log' ]->debug ( print_r ( $this->_viewdefs [ 'panels' ], true ) ) ;
478
479     }
480
481     /*  Convert our internal format back to the standard Canonical MetaData layout
482      *  First non-(empty) field goes in at column 0; all other (empty)'s removed
483      *  Studio required fields are also added to the layout.
484      *  Do this AFTER reading in all the $_REQUEST parameters as can't guarantee the order of those, and we need to operate on complete rows
485      */
486     protected function _convertToCanonicalForm ( $panels , $fielddefs )
487     {
488         $previousViewDef = $this->getFieldsFromLayout($this->implementation->getViewdefs ());
489         $oldDefs = $this->implementation->getViewdefs ();
490         $currentFields = $this->getFieldsFromLayout($this->_viewdefs);
491         foreach($fielddefs as $field => $def)
492         {
493                 if (self::fieldIsRequired($def) && !isset($currentFields[$field]))
494                 {
495                 //Use the previous viewdef if this field was on it.
496                 if (isset($previousViewDef[$field]))
497                 {
498                     $def = $previousViewDef[$field];
499                 }
500                 //next see if the field was on the original layout.
501                 else if (isset ($this->_originalViewDef [ $field ]))
502                 {
503                     $def = $this->_originalViewDef [ $field ] ;   
504                 }
505                 //Otherwise make up a viewdef for it from field_defs
506                 else
507                 {
508                     $def =  self::_trimFieldDefs( $def ) ;
509                 }
510                 $this->addField($def);
511                 }
512         }
513         
514         foreach ( $panels as $panelID => $panel )
515         {
516             // remove all (empty)s
517             foreach ( $panel as $rowID => $row )
518             {
519                 $startOfRow = true ;
520                 $offset = 0 ;
521                 foreach ( $row as $colID => $fieldname )
522                 {
523                     if ($fieldname == MBConstants::$EMPTY[ 'name' ])
524                     {
525                         // if a leading (empty) then remove (by noting that remaining fields need to be shuffled along)
526                         if ($startOfRow)
527                         {
528                             $offset ++ ;
529                         }
530                         unset ( $row [ $colID ] ) ;
531                     } else
532                     {
533                         $startOfRow = false ;
534                     }
535                 }
536
537                 // reindex to remove leading (empty)s and replace fieldnames by full definition from fielddefs
538                 $newRow = array ( ) ;
539                 foreach ( $row as $colID => $fieldname )
540                 {
541                         if ($fieldname == null)
542                            continue;
543                     
544                     //Backwards compatibility and a safeguard against multiple calls to _convertToCanonicalForm
545                            if(is_array($fieldname))
546                     {
547                         $newRow [ $colID - $offset ] = $fieldname;
548                         continue;
549                     }
550                         
551                         //Replace (filler) with the empty string
552                         if ($fieldname == $this->FILLER[ 'name' ]) {
553                         $newRow [ $colID - $offset ] = '' ;
554                     }
555                     //Use the previous viewdef if this field was on it.
556                                         else if (isset($previousViewDef[$fieldname]))
557                         {
558                                  $newRow [ $colID - $offset ] = $previousViewDef[$fieldname];
559                         //We should copy over the tabindex if it is set.
560                         if (isset ($fielddefs [ $fieldname ]) && !empty($fielddefs [ $fieldname ]['tabindex']))
561                             $newRow [ $colID - $offset ]['tabindex'] = $fielddefs [ $fieldname ]['tabindex'];
562                         }
563                     //next see if the field was on the original layout.
564                     else if (isset ($this->_originalViewDef [ $fieldname ]))
565                     {
566                         $newRow [ $colID - $offset ] = $this->_originalViewDef [ $fieldname ] ;  
567                         //We should copy over the tabindex if it is set.
568                         if (isset ($fielddefs [ $fieldname ]) && !empty($fielddefs [ $fieldname ]['tabindex']))
569                             $newRow [ $colID - $offset ]['tabindex'] = $fielddefs [ $fieldname ]['tabindex']; 
570                     }
571                         //Otherwise make up a viewdef for it from field_defs
572                         else if (isset ($fielddefs [ $fieldname ]))
573                         {
574                                 $newRow [ $colID - $offset ] =  self::_trimFieldDefs( $fielddefs [ $fieldname ] ) ;
575                                 
576                         }
577                         //No additional info on this field can be found, jsut use the name;
578                         else 
579                         {
580                         $newRow [ $colID - $offset ] = $fieldname;
581                         }
582                 }
583                 $panels [ $panelID ] [ $rowID ] = $newRow ;
584             }
585         }
586         
587         return $panels ;
588     }
589
590     /*
591      * Convert from the standard MetaData format to our internal format
592      * Replace NULL with (filler) and missing entries with (empty)
593      */
594     protected function _convertFromCanonicalForm ( $panels , $fielddefs )
595     {
596         if (empty ( $panels ))
597             return ;
598
599         // Fix for a flexibility in the format of the panel sections - if only one panel, then we don't have a panel level defined,
600                 // it goes straight into rows
601         // See EditView2 for similar treatment
602         if (! empty ( $panels ) && count ( $panels ) > 0)
603         {
604             $keys = array_keys ( $panels ) ;
605             if (is_numeric ( $keys [ 0 ] ))
606             {
607                 $defaultPanel = $panels ;
608                 unset ( $panels ) ; //blow away current value
609                 $panels [ 'default' ] = $defaultPanel ;
610             }
611         }
612
613         $newPanels = array ( ) ;
614
615         // replace '' with (filler)
616         foreach ( $panels as $panelID => $panel )
617         {
618             foreach ( $panel as $rowID => $row )
619             {
620                 $cols = 0;
621                 foreach ( $row as $colID => $col )
622                 {
623                     if ( ! empty ( $col ) )
624                     {
625                         if ( is_string ( $col ))
626                         {
627                             $fieldname = $col ;
628                         } else if (! empty ( $col [ 'name' ] ))
629                         {
630                             $fieldname = $col [ 'name' ] ;
631                         }
632                     } else
633                     {
634                         $fieldname = $this->FILLER['name'] ;
635                     }
636
637                     $newPanels [ $panelID ] [ $rowID ] [ $cols ] = $fieldname ;
638                     $cols++;
639                 }
640             }
641         }
642
643         // replace missing fields with (empty)
644         foreach ( $newPanels as $panelID => $panel )
645         {
646             $column = 0 ;
647             foreach ( $panel as $rowID => $row )
648             {
649                 // pad between fields on a row
650                 foreach ( $row as $colID => $col )
651                 {
652                     for ( $i = $column + 1 ; $i < $colID ; $i ++ )
653                     {
654                         $row [ $i ] = MBConstants::$EMPTY ['name'];
655                     }
656                     $column = $colID ;
657                 }
658                 // now pad out to the end of the row
659                 if (($column + 1) < $this->getMaxColumns ())
660                 { // last column is maxColumns-1
661                     for ( $i = $column + 1 ; $i < $this->getMaxColumns () ; $i ++ )
662                     {
663                         $row [ $i ] = MBConstants::$EMPTY ['name'] ;
664                     }
665                 }
666                 ksort ( $row ) ;
667                 $newPanels [ $panelID ] [ $rowID ] = $row ;
668             }
669         }
670
671         return $newPanels ;
672     }
673     
674     protected function getFieldsFromLayout($viewdef) {
675         if (isset($viewdef['panels']))
676         {
677                 $panels = $viewdef['panels']; 
678         } else {
679         $panels = $viewdef[self::$variableMap [ $this->_view ] ]['panels']; 
680         }
681         
682         $ret = array();
683         if (is_array($panels)) 
684         {       
685                 foreach ( $panels as $rows) {
686                     foreach ($rows as $fields) {
687                         //wireless layouts have one less level of depth
688                         if (is_array($fields) && isset($fields['name'])) {
689                                 $ret[$fields['name']] = $fields;  
690                                 continue;
691                         }
692                         if (!is_array($fields)) {
693                                 $ret[$fields] = $fields;
694                                 continue;
695                         }
696                         foreach ($fields as $field) {
697                             if (is_array($field) && !empty($field['name']))
698                             {
699                                 $ret[$field['name']] = $field;  
700                             }
701                             else if(!is_array($field)){
702                             $ret[$field] = $field;
703                         }                           
704                         }
705                     }
706                 }
707         }
708         return $ret;
709     }
710     
711     protected function fieldIsRequired($def)
712     {
713         if (isset($def['studio']))
714         { 
715                 if (is_array($def['studio']))
716                 {
717                         if (!empty($def['studio'][$this->_view]) && $def['studio'][$this->_view] == "required")
718                         {
719                                 return true;
720     }
721                         else if (!empty($def['studio']['required']) && $def['studio']['required'] == true)
722                         {
723                                 return true;
724                         }
725                 }
726                 else if ($def['studio'] == "required" ){
727                   return true;
728                 }
729     }
730         return false;
731     }
732
733     static function _trimFieldDefs ( $def )
734         {
735                 $ret = array_intersect_key ( $def , 
736             array ( 'studio' => true , 'name' => true , 'label' => true , 'displayParams' => true , 'comment' => true , 
737                     'customCode' => true , 'customLabel' => true , 'tabindex' => true , 'hideLabel' => true) ) ;
738         if (!empty($def['vname']) && empty($def['label']))
739             $ret['label'] = $def['vname'];
740                 return $ret;
741         }
742         
743         public function getUseTabs(){
744         if (isset($this->_viewdefs  [ 'templateMeta' ]['useTabs']))
745            return $this->_viewdefs  [ 'templateMeta' ]['useTabs'];
746            
747         return false;
748     }
749     
750     public function setUseTabs($useTabs){
751         $this->_viewdefs  [ 'templateMeta' ]['useTabs'] = $useTabs;
752     }
753     
754     /**
755      * Return whether the Detail & EditView should be in sync.
756      */
757         public function getSyncDetailEditViews(){
758         if (isset($this->_viewdefs  [ 'templateMeta' ]['syncDetailEditViews']))
759            return $this->_viewdefs  [ 'templateMeta' ]['syncDetailEditViews'];
760            
761         return false;
762     }
763     
764     /**
765      * Sync DetailView & EditView. This should only be set on the EditView
766      * @param bool $syncViews
767      */
768     public function setSyncDetailEditViews($syncDetailEditViews){
769         $this->_viewdefs  [ 'templateMeta' ]['syncDetailEditViews'] = $syncDetailEditViews;
770     }
771
772     /**
773      * Getter function to get the implementation method which is a private variable
774      * @return DeployedMetaDataImplementation
775      */
776     public function getImplementation(){
777         return $this->implementation;
778     }
779
780     /**
781      * Public access to _convertFromCanonicalForm
782      * @param  $panels
783      * @param  $fielddefs
784      * @return array
785      */
786     public function convertFromCanonicalForm ( $panels , $fielddefs )
787     {
788         return $this->_convertFromCanonicalForm ( $panels , $fielddefs );
789     }
790
791      /**
792      * Public access to _convertToCanonicalForm
793      * @param  $panels
794      * @param  $fielddefs
795      * @return array
796      */
797     public function convertToCanonicalForm ( $panels , $fielddefs )
798     {
799         return $this->_convertToCanonicalForm ( $panels , $fielddefs );
800     }
801
802     
803     /**
804      * @return Array list of fields in this module that have the calculated property
805      */
806     public function getCalculatedFields() {
807         $ret = array();
808         foreach ($this->_fielddefs as $field => $def)
809         {
810             if(!empty($def['calculated']) && !empty($def['formula']))
811             {
812                 $ret[] = $field;
813             }
814         }
815         
816         return $ret;
817     }
818
819     /**
820      * @return Array fields in the given panel
821      */
822     public function getFieldsInPanel($targetPanel) {
823         return iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($this->_viewdefs['panels'][$targetPanel])));
824     }
825 }
826
827 ?>