Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 59
CRAP
0.00% covered (danger)
0.00%
0 / 288
TTreeView
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 59
20592
0.00% covered (danger)
0.00%
0 / 288
 __construct
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 27
 setXmlFile
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getXmlFile
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 18
 show
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 setOnClick
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 getOnClick
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnDblClick
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 getOnDblClick
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnCheck
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getOnCheck
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 enableCheck
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 4
 getEnableCheck
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getOnDragEnd
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 enableDrag
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 4
 getEnableDrag
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 enableLines
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getEnableLines
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setData
0.00% covered (danger)
0.00%
0 / 1
132
0.00% covered (danger)
0.00%
0 / 20
 addFormSearchFields
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 6
 getFormSearchFields
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 5
 setInitialParentKey
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getInitialParentKey
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 2
 setEnableHighlighting
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getEnableHighlighting
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 setImagesPath
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getImagesPath
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 3
 setTheme
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 4
 getTheme
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setRootLabel
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 5
 getRootLabel
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setStartExpanded
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getStartExpanded
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getItemIsOpen
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 5
 addItem
0.00% covered (danger)
0.00%
0 / 1
156
0.00% covered (danger)
0.00%
0 / 23
 clear
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 6
 removeAll
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 setToolBar
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 12
 getJs
0.00% covered (danger)
0.00%
0 / 1
506
0.00% covered (danger)
0.00%
0 / 42
 setShowToolBar
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getShowToolBar
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 showToolBar
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 hideToolBar
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 addOrphan
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 6
 getOrphanById
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 getOrphanByIdParent
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 8
 getOrphans
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setParentFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getParentFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setChildFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getChildFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setDescFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getDescFieldName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setTableName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getTableName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setMixData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getMixData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setUserDataFieldNames
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getUserDataFieldNames
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getXml
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 16
1<?php
2/*
3 * Formdin Framework
4 * Copyright (C) 2012 Ministério do Planejamento
5 * Criado por Luís Eugênio Barbosa
6 * Essa versão é um Fork https://github.com/bjverde/formDin
7 *
8 * ----------------------------------------------------------------------------
9 * This file is part of Formdin Framework.
10 *
11 * Formdin Framework is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License version 3
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License version 3
21 * along with this program; if not,  see <http://www.gnu.org/licenses/>
22 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
23 * Fifth Floor, Boston, MA  02110-1301, USA.
24 * ----------------------------------------------------------------------------
25 * Este arquivo é parte do Framework Formdin.
26 *
27 * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou
28 * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
29 * do Software Livre (FSF).
30 *
31 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
32 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
33 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
34 * para maiores detalhes.
35 *
36 * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
37 * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
38 * ou escreva para a Fundação do Software Livre (FSF) Inc.,
39 * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
40 */
41
42/*
43    Estrutura do xml - http://docs.dhtmlx.com/doku.php?id=dhtmlxtree:syntax_templates
44    API - http://docs.dhtmlx.com/doku.php?id=dhtmlxtree:api_toc_categories
45    Componente: http://docs.dhtmlx.com/doku.php?id=dhtmlxtree:toc
46*/
47class TTreeView extends TControl
48{
49    private $itens;
50    private $xmlFile;
51    private $onClick;    // recebe o ID do item clicado
52    private $onDblClick; // recebe o ID do item clicado
53    private $onDragEnd;  // recebe o ID do ítem de origem e o ID do ítem destino
54    private $onCheck;    // recebe o ID e o state do check box do ítem. State = 0 ou 1
55    private $enableCheckBoxes;
56    //private $enableRadiobuttons;
57    private $enableDragAndDrop;
58    private $enableTreeLines;
59    private $formSearchFields;
60    private $initialParentKey;
61    private $enableHighlighting;
62    private $imagesPath;
63    private $theme;
64    private $userDataFieldNames;
65    private $rootLabel;
66    private $rootNode;
67    private $startExpanded;
68    private $toolBarVisible;
69    private $arrOrphan;
70
71    private $parentFieldName;
72      private $childFieldName;
73      private $descFieldName;
74      private $tableName;
75      private $mixData;
76
77    /**
78    * Implementa Tree View
79    *
80    * O parametro $mixData pode ser um array de dados
81    *
82    * A função definida no parametro jsOnClick recebe o id do item clicado e deve ser utilizado para
83    * recuperar attributos do nó.
84    * <code>
85    *     alert( tree.getSelectedItemId());
86    *     alert( tree.getItemText(id ) );
87    *     alert( tree.getUserData(id,'URL') );
88    * </code>
89    *
90    * A função definida no parametro jsOnDblClick recebe o id do item duplamente clicado e deve ser utilizado para
91    * recuperar attributos do nó.
92    * <code>
93    *     alert( tree.getSelectedItemId());
94    *     alert( tree.getItemText(id ) );
95    *     alert( tree.getUserData(id,'URL') );
96    * </code>
97    *
98    * A função definida no parametro jsOnCheck recebe o id e o state do item clicado.
99    * <code>
100    *     function treeCheck(id, state)
101    *     {
102    *         alert( state );
103    *     }
104    * </code>
105    *
106    * A função definida no parametro jsOnDrag recebe o id do item arrastado e o id do item destino, se retornar true a operação e aceita
107    * <code>
108    *     function treeDrag(id, id2) {
109    *        return confirm("Deseja mover o ítem " + tree.getItemText(id) + " para o item " + tree.getItemText(id2) + "?");
110    *    };
111    * </code>
112    *
113    * @param mixed $strName               - 1: id do campo
114    * @param string $strRootLabel         - 2: Lavel do campo
115    * @param mixed $mixData               - 3: array de dados
116    * @param mixed $strParentFieldName    - 4: id do campo chave do pai
117    * @param mixed $strChildFieldName     - 5: id do campo chave dos filhos
118    * @param mixed $strDescFieldName      - 6: Texto da descrição dos nos da arvore
119    * @param mixed $strInitialParentKey   -07:
120    * @param mixed $mixUserDataFieldNames -08: campos separados por virgula ou array normal ex: array('nome','telefone');
121    * @param mixed $strHeight             -09: altura
122    * @param mixed $strWidth              -10: largura
123    * @param mixed $jsOnClick             -11:
124    * @param mixed $jsOnDblClick          -12:
125    * @param mixed $jsOnCheck             -13:
126    * @param mixed $jsOnDrag              -14:
127    * @param mixed $boolEnableCheckBoxes  -15:
128    * @param mixed $boolEnableRadioButtons-16:
129    * @param mixed $boolEnableTreeLines   -17:
130    * @param mixed $mixFormSearchFields   -18:
131    * @param mixed $boolShowToolBar       -19:
132    * @param mixed $startExpanded         -20: Se o treeView deve aparecer expandido ou não.
133    * @return TTreeView
134    */
135    public function __construct( $strName=null, $strRootLabel = null, $mixData = null
136                               , $strParentFieldName = null, $strChildFieldName = null
137                               , $strDescFieldName = null, $strInitialParentKey = null
138                               , $mixUserDataFieldNames = null, $strHeight = null, $strWidth = null
139                               , $jsOnClick = null
140                               , $jsOnDblClick = null
141                               , $jsOnCheck = null
142                               , $jsOnDrag = null
143                               , $boolEnableCheckBoxes = null
144                               , $boolEnableRadioButtons = null
145                               , $boolEnableTreeLines = null
146                               , $mixFormSearchFields = null
147                               , $boolShowToolBar = null
148                               , $startExpanded = null)
149    {
150        $strName = is_null($strName) ? 'tree_'.$this->getRandomChars(3):$strName;
151        parent::__construct( 'div', $strName );
152        $this->setFieldType( 'treeview' );
153        $this->setClass( 'fwTreeView' );
154        $this->setStartExpanded($startExpanded);
155        $this->setOnClick( $jsOnClick );
156        $this->setOnDblClick( $jsOnDblClick );
157        $this->setOnCheck( $jsOnCheck );
158        $this->setWidth( $strWidth );
159        $this->setHeight( $strHeight );
160        $this->enableCheck( $boolEnableCheckBoxes );
161        $this->enableDrag( !is_null( $jsOnDrag ), $jsOnDrag );
162        $this->setInitialParentKey( $strInitialParentKey );
163        $this->setEnableHighlighting( true );
164        $this->setRootLabel( $strRootLabel );
165        $this->setShowToolBar( $boolShowToolBar );
166        //$this->initialParentKey = $strInitialParentKey;
167        //$this->enableRadio($boolEnableRadioButtons);
168        $this->addFormSearchFields( $mixFormSearchFields );
169        $this->enableLines( $boolEnableTreeLines );
170        $this->setMixData($mixData);
171        if ( is_string( $mixData ) )
172        {
173            $this->setTableName($mixData);
174        }
175        //$this->setData( $mixData, $strParentFieldName, $strChildFieldName, $strDescFieldName, $mixUserDataFieldNames );
176        $this->setParentFieldName($strParentFieldName);
177         $this->SetChildFieldName($strChildFieldName);
178         $this->setDescFieldName($strDescFieldName);
179         $this->setUserDataFieldNames($mixUserDataFieldNames);
180         $this->setData();
181    }
182
183    /**
184    * Define o arquivo externo para criação dinâmica da árvore quando o ítem for expandido.
185    *
186    * Se for definido os parametros $mixData,$strParentFieldName,$strChildFieldName,$strDescFieldName, a classe
187    * utilizará automaticamente o arquivo genérico base/callbacks/treeView.php para obter os valores via ajax
188
189    * <code>
190    *     $tree->setXmlFile('index.php?modulo=base/exemplos/tree.php&ajax=1');
191    * </code>
192    * @param mixed $strFileName
193    */
194    public function setXmlFile( $strFileName = null )
195    {
196        $this->xmlFile = $strFileName;
197    }
198
199    public function getXmlFile()
200    {
201        $itens = $this->itens;
202        if( !$itens ) {
203               $xmlFile = is_null($this->xmlFile) ? $this->getBase().'callbacks/treeView.php' : $this->xmlFile;
204               if( file_exists($xmlFile) ) {
205                   $parentFieldName = $this->getParentFieldName();
206                   $childFieldName = $this->getChildFieldName();
207                   $descFieldName = $this->getDescFieldName();
208                   $tableName = $this->getTableName();
209                   $userDataFieldNames = $this->getUserDataFieldNames();
210                   $url = 'index.php?modulo='.$xmlFile
211                           .'&ajax=1&fwTreeview=1&parentField='.$parentFieldName
212                           .'&childField='.$childFieldName
213                           .'&descField='.$descFieldName
214                           .'&tableName='.$tableName
215                           .'&userDataFields='.$userDataFieldNames;
216                   return $url;
217            } else {
218                $this->addItem(0,1,'Arquivo '.$xmlFile.' não encontrado!', true, '' );
219            }
220        }
221    }
222
223    
224    public function show( $print = true )
225    {
226        //$this->setData();
227        $this->setToolBar();
228        return parent::show( $print );
229    }
230    /**
231    * Define a função que será chamada quando o usuário clicar em um ítem da árvore.
232    * Esta função recebe o id do ítem clicado
233    * Exemplo: alert( tree.getItemText(id) );
234    *
235    * @param mixed $strJsFuncion
236    */
237    public function setOnClick( $strJsFunction = null )
238    {
239        $this->onDblClick = null;
240        $this->onClick = $strJsFunction;
241    }
242
243    public function getOnClick()
244    {
245        return $this->removeIllegalChars( $this->onClick, '.' );
246    }
247    /**
248    * Define a função que será chamada quando o usuário fizer um duplo clique em um ítem da árvore.
249    * Esta função recebe o id do ítem clicado
250    * Exemplo: alert( tree.getItemText(id) );
251    *
252    * @param mixed $strJsFuncion
253    */
254    public function setOnDblClick( $strJsFunction = null )
255    {
256        $this->onClick = null;
257        $this->onDblClick = $strJsFunction;
258    }
259
260    public function getOnDblClick()
261    {
262        return $this->removeIllegalChars( $this->onDblClick, '.' );
263    }
264    /**
265    * Define o nome de uma função javascript que será chamada ao clicar no checkbox
266    * Esta função receberá dois parametros: o ID do state do checkbox sendo 0 ou 1
267    *
268    * @param mixed $strJsFunction
269    */
270    public function setOnCheck( $strJsFunction = null )
271    {
272        $this->onCheck = $strJsFunction;
273    }
274
275    public function getOnCheck()
276    {
277        return $this->removeIllegalChars( $this->onCheck, '.' );
278    }
279
280    public function enableCheck( $boolNewValue = null )
281    {
282        $boolNewValue = $boolNewValue === true ? true : false;
283        $this->enableCheckBoxes = $boolNewValue;
284
285        if ( $this->enableCheckBoxes )
286        {
287        //$this->enableRadiobuttons=false;
288        }
289    }
290
291    public function getEnableCheck()
292    {
293        return $this->enableCheckBoxes;
294    }
295    /*public function enableRadio($boolNewValue=null)
296    {
297        $boolNewValue = $boolNewValue===true ? true : false;
298        $this->enableRadiobuttons = $boolNewValue;
299        if( $this->enableRadiobuttons )
300        {
301            $this->enableCheckBoxes=false;
302        }
303    }
304    */
305    /*blic function getEnableRadio()
306    {
307        return $this->enableRadiobuttons;
308    }
309    */
310    public function getOnDragEnd()
311    {
312        return $this->removeIllegalChars( $this->onDragEnd, '.' );
313    }
314    /**
315    * Habilita/Desabilita o recurso de arrastar e soltar
316    *
317    * A função de callback recebe os IDs dos ítens origem e destino, se for
318    * returnado false a operação é cancelada
319    * Exemplo:     return confirm("Deseja mover o ítem " + tree.getItemText(id) + " para o item " + tree.getItemText(id2) + "?");
320    *
321    * @param boolean $boolNewValue
322    * @param string $strJsCallBack
323    */
324    public function enableDrag( $boolNewValue = null, $strJsCallBack = null )
325    {
326        $boolNewValue = $boolNewValue === true ? true : false;
327        $this->enableDragAndDrop = $boolNewValue;
328        $this->onDragEnd = $strJsCallBack;
329    }
330
331    public function getEnableDrag()
332    {
333        return $this->enableDragAndDrop;
334    }
335    /**
336    * Permite mostra ou esconder as linhas de desenho dos níveis da treeview
337    *
338    * @param boolean $boolNewValue
339    */
340    public function enableLines( $boolNewValue = null )
341    {
342        $boolNewValue = $boolNewValue === true ? true : false;
343        $this->enableTreeLines = $boolNewValue;
344    }
345
346    //---------------------------------------------------------------------------
347    public function getEnableLines()
348    {
349        return $this->enableTreeLines;
350    }
351
352    //---------------------------------------------------------------------------
353    public function setData()
354    {
355        $arrData = $this->getMixData();
356        $strParentField = $this->getParentFieldName();
357        $strChildField = $this->getChildFieldName();
358        $strDescField = $this->getDescFieldName();
359        $mixUserDataFields = $this->getUserDataFieldNames();
360        
361        if ( !is_array( $arrData ) || is_null( $strParentField ) || is_null( $strChildField ) || is_null( $strDescField ) )
362        {
363            return;
364        }
365
366        // construir valores do parametro UserData
367        if ( is_string( $mixUserDataFields ) )
368        {
369            $mixUserDataFields = explode( ',', $mixUserDataFields );
370        }
371
372        foreach( $arrData[ $strParentField ] as $k => $v )
373        {
374            $arrUserData = null;
375
376            if ( is_array( $mixUserDataFields ) ) {
377                foreach( $mixUserDataFields as $kData => $vData ) {
378                    if ( isset( $arrData[ trim( $vData )] ) ) {
379                        $arrUserData[ trim( $vData )] = $arrData[ trim( $vData )][ $k ];
380                    }
381                }
382            }
383
384            if ( ( string ) $v == '' ){
385                $this->addItem( 0, $arrData[ $strChildField ][ $k ], $arrData[ $strDescField ][ $k ], null, null, $arrUserData );
386            }else{
387                $expand = $this->getItemIsOpen(null, null, null, null);
388                $this->addItem( $v, $arrData[ $strChildField ][ $k ], $arrData[ $strDescField ][ $k ],  $expand, null, $arrUserData );
389            }
390        }
391    }
392
393    //---------------------------------------------------------------------------
394    /**
395    * Método para adicionar campos do formulário como parametro de filtragem nos
396    * dados retornados para construção da árvore.
397    * Se o valor for passado, este será constante, se for nulo será o valor atual do
398    * campo no formulário.
399    *
400    * @param mixed $mixFieldId
401    * @param mixed $strValue
402    */
403    public function addFormSearchFields( $mixFieldId = null, $strValue = null )
404    {
405        if ( is_null( $mixFieldId ) || $mixFieldId == '' )
406        {
407            return;
408        }
409
410        if ( is_array( $mixFieldId ) )
411        {
412            $this->formSearchFields = $mixFieldId;
413        }
414        else
415        {
416            $this->formSearchFields[ $mixFieldId ] = $strValue;
417        }
418    }
419
420    //---------------------------------------------------------------------------
421    public function getFormSearchFields( $boolJson = null )
422    {
423        if ( !$boolJson )
424        {
425            return $this->formSearchFields;
426        }
427
428        if ( is_array( $this->formSearchFields ) )
429        {
430            return json_encode( $this->formSearchFields );
431        }
432    }
433
434    //---------------------------------------------------------------------------
435    public function setInitialParentKey( $mixNewValue = null )
436    {
437        $this->initialParentKey = $mixNewValue;
438    }
439    public function getInitialParentKey()
440    {
441        $id = isset( $_REQUEST['id'] ) ? $_REQUEST['id'] : '0';
442        return is_null($this->initialParentKey) ? $id : $this->initialParentKey;
443    }
444
445    //---------------------------------------------------------------------------
446    public function setEnableHighlighting( $boolNewValue = null )
447    {
448        $this->enableHighlighting = $boolNewValue;
449    }
450
451    public function getEnableHighlighting()
452    {
453        if ( $this->enableHighlighting === false )
454        {
455            return 0;
456        }
457        else
458        {
459            return 1;
460        }
461    }
462
463    //---------------------------------------------------------------------------
464    function setImagesPath( $strNewValue = null )
465    {
466        $this->imagesPath = $strNewValue;
467    }
468
469    function getImagesPath()
470    {
471        if ( is_null( $this->imagesPath ) || !file_exists( $this->imagesPath ) )
472        {
473            return $this->getBase() . 'js/dhtmlx/treeview/imgs/' . $this->getTheme() . '/';
474        }
475        return $this->imagesPath;
476    }
477
478    //---------------------------------------------------------------------------
479    /**
480    * define o tema da treeview
481    *
482    * @param array $strNewTheme
483    */
484    public function setTheme( $strNewTheme = 'default|vista|skyblue|winstyle' )
485    {
486        if ( preg_match( '/\|/', $strNewTheme ) > 0 )
487        {
488            $strNewTheme = null;
489        }
490        $this->theme = $strNewTheme;
491    }
492
493    public function getTheme()
494    {
495        return is_null( $this->theme ) ? 'default' : $this->theme;
496    }
497
498    //---------------------------------------------------------------------------
499    public function setRootLabel( $strNewValue = null )
500    {
501        if (!is_null($this->rootNode))
502        {
503            echo 'Função setRootLabel() classe TTreeview só pode ser utilizada enquanto a árvore está vazia.';
504            return;
505        }
506        $this->rootLabel = $strNewValue;
507    }
508
509    public function getRootLabel()
510    {
511        return $this->rootLabel;
512    }
513
514    //---------------------------------------------------------------------------
515    public function setStartExpanded( $boolNewValue = null )
516    {
517        //echo '<hr>';
518        //echo '$boolNewValue:'.$boolNewValue;
519        //var_dump($boolNewValue);
520        //echo '<hr>';
521        $boolNewValue = is_null( $boolNewValue ) ? false : $boolNewValue;
522        $this->startExpanded = $boolNewValue;
523    }
524
525    public function getStartExpanded()
526    {
527        return $this->startExpanded;
528    }
529
530    
531    protected function getItemIsOpen( $open = null, $idParent = null, $id = null, $text = null )
532    {
533        $expand = false;
534        if ( !is_null($open) ){
535            $expand = $open;
536        }else{
537            $expand = is_null( $this->getStartExpanded() ) ? true : $this->getStartExpanded();
538        }
539        //echo '<hr>';
540        //echo 'id:'.$id.', idParent:'.$idParent.', text:'.$text.', $open: '.$open.', $expand: '.$expand.', $expandObj: '.$this->getStartExpanded();
541        //var_dump($id,$idParent,$text,$open,$expand,$this->getStartExpanded());
542        return $expand;
543    }
544    
545    //---------------------------------------------------------------------------
546    /**
547    * Adicionar ítem na árvore
548    *
549    * @param mixed $idParent       1: id do registro pai
550    * @param mixed $id             2: id do registro
551    * @param mixed $text           3: Texto do Registro
552    * @param mixed $open           4: Nó aberto ou fechado
553    * @param mixed $hint           5: 
554    * @param mixed $arrUserData    6: campos que serão passados quando clicamos no nó da arvore, usado no TreeClik
555    * @param mixed $boolSelect
556    * @param mixed $boolChecked
557    */
558    public function addItem( $idParent, string $id, string $text, $open = null, $hint = null, $arrUserData = null, $boolSelect = null, $boolChecked = null )
559    {
560        $idParent = is_null($idParent) ? '' : $idParent.'';
561         if ( !$this->itens ) {
562
563             $expand = $this->getItemIsOpen($open, $idParent, $id, $text);
564            if( $idParent == $this->initialParentKey && ! isset($_REQUEST['id'] ) ) {                
565                if ( $this->getRootLabel() ) {
566                    $this->itens = new TTreeViewData( '0', 'root', true, '' ); // nivel obrigatório
567                    $this->itens->addItem($this->rootNode = new TTreeViewData( $this->getRandomChars(10)  , $this->getRootLabel(), true, 'Item Raiz' )); //raiz
568                }
569                else {
570                    $this->itens = $this->rootNode = new TTreeViewData( '0', 'root', $expand, '' ); // nivel obrigatório
571                }
572            } else {
573                $this->itens = $this->rootNode = new TTreeViewData( $idParent, 'root', $expand, '' ); // nivel obrigatório
574            }
575
576        }
577        $parent = ( is_null($idParent) || $idParent=="" || $idParent == '0') ? $this->rootNode : $this->itens->getElementById( $idParent );
578         if ( !$parent )
579        {
580            $expand = $this->getItemIsOpen($open, $idParent, $id, $text);
581            $item = New TTreeViewData( $id, $text, $expand, $hint, $arrUserData, $boolSelect );
582            $item->setParent( $idParent );
583            $this->addOrphan( $item );
584            return;
585        }
586        if ( $id === '0' )
587        {
588            echo 'Função addItem() da classe TTreeview não permite ítem com ID = 0 (ZERO).';
589            return;
590        }
591        // adicionar filho somente se não existir
592        if ( !$item = $this->itens->getElementById( $id ) )
593        {
594            $expand = $this->getItemIsOpen($open, $idParent, $id, $text);
595            $parent->addItem( new TTreeViewData( $id, $text, $expand, $hint, $arrUserData, $boolSelect, $boolChecked ) );
596        }
597    }
598    //---------------------------------------------------------------------------
599    function clear() {
600        parent::clear();
601        if ($this->rootNode)
602            $this->rootNode->clear();
603        $this->rootNode = null;
604        $this->itens = null;
605    }
606    //---------------------------------------------------------------------------
607    function removeAll() {
608        $this->clear();
609    }
610    //---------------------------------------------------------------------------
611    protected function setToolBar()
612    {
613        if ( $this->getShowToolBar() )
614        {
615            $tb = new TElement( 'div' );
616            $tb->setClass( 'fwTreeViewToolBar' );
617            $tb->setId( $this->getId() . '_toolbar' );
618            $tb->add( new TButton( $tb->getId() . '_btn1', null, null, $this->getId() . 'Js.openAllItems(0)', null, 'folderAzulOpen.gif', null, 'Expandir Todos' ) );
619            $tb->add( new TButton( $tb->getId() . '_btn2', null, null, $this->getId() . 'Js.closeAllItems(0)', null, 'folderAzul.gif', null, 'Fechar Todos' ) );
620
621            if ( $this->getEnableCheck() )
622            {
623                $tb->add( new TButton( $tb->getId() . '_btn3', null, null, 'if(!' . $this->getId() . 'Js.getSelectedItemId()){alert("Selecione um ítem");return false;}' . $this->getId() . 'Js.setSubChecked(' . $this->getId() . 'Js.getSelectedItemId(),true)', null, 'iconCheckAll.gif', null, 'Marcar o ítem e seus descendentes' ) );
624                $tb->add( new TButton( $tb->getId() . '_btn4', null, null, 'if(!' . $this->getId() . 'Js.getSelectedItemId()){alert("Selecione um item");return false;}' . $this->getId() . 'Js.setSubChecked(' . $this->getId() . 'Js.getSelectedItemId(),false)', null, 'iconUncheckAll.gif', null, 'Desmarcar o ítem e seus descendentes' ) );
625            }
626            $this->add( $tb );
627            $this->setCss( 'overflow', 'auto' );
628        }
629    }
630
631    //---------------------------------------------------------------------------
632    public function getJs()
633    {
634
635        $id = $this->getId() . "Js";
636        $js = $id . ' = new dhtmlXTreeObject("' . $this->getId() . '", "100%", "100%", 0);' . "\n";
637        //$js .= $this->getId().".setSkin('dhx_skyblue');"."\n";
638        //$js .= $this->getId().'.setImagePath("'.$this->getBase().'js/dhtmlx/codebase/imgs/csh_bluebooks/");'."\n";
639        $js .= $id . '.setImagePath("' . $this->getImagesPath() . '");' . "\n";
640        $js .= $id . '.enableHighlighting(' . $this->getEnableHighlighting() . ');' . "\n";
641
642        $xmlFile = $this->getXmlFile();
643        if ( $xmlFile ){
644            $js .= $id . '.attachEvent("onXLS", function(tree,id){fwTreeAddLoading(tree,id);});' . "\n";
645            $js .= $id . '.attachEvent("onXLE", function(tree,id){fwTreeRemoveLoading(tree,id);});' . "\n";
646        }
647
648        if ( $this->getOnClick() ){
649            $js .= $id . '.setOnClickHandler( ' . $this->getOnClick() . ' );' . "\n";
650        } else if( $this->getOnDblClick() ) {
651            $js .= $id . '.setOnDblClickHandler( ' . $this->getOnDblClick() . ' );' . "\n";
652        }
653
654        if ( $this->getEnableCheck() ){
655            $js .= $id . '.enableCheckBoxes(true);' . "\n";
656        }
657
658        //if($this->getEnableRadio() )
659        //{
660        //$js .= $id.'.enableRadiobuttons(true);'."\n";
661        //}
662        if ( $this->getEnableDrag() )
663        {
664            // Parametro false = não pode soltar em uma area vazia da arvore, somente sobre outro item
665            $js .= $id . '.enableDragAndDrop(1,false);' . "\n";
666        }
667
668        if ( $this->getOnDragEnd() )
669        {
670            $js .= $id . '.setDragHandler( ' . $this->getOnDragEnd() . ' );' . "\n";
671        }
672
673        if ( $this->getOnCheck() )
674        {
675            $js .= $id . '.setOnCheckHandler( ' . $this->getOnCheck() . ' );' . "\n";
676        }
677
678        if ( $this->getEnableLines() )
679        {
680            $js .= $id . '.enableTreeLines(true);' . "\n";
681        }
682
683        if ( $xmlFile ){
684            $url = $xmlFile;
685            $url = str_replace( 'index.php', '', $url );
686            if ( !strpos( $url, 'ajax=1' ) )
687            {
688                $url .= ( strpos( $url, '?' ) > 0 ? '&' : '?' ) . 'ajax=1';
689            }
690            if ( $this->initialParentKey )
691            {
692                $url .= '&initialParentKey=' . $this->initialParentKey;
693            }
694
695            if ( strpos( $xmlFile, 'index.php' ) == 0 ) {
696                $js .= $id . '.setXMLAutoLoading(fwUrlAddParams(app_url+app_index_file+"' . $url . '"' . ( $this->getFormSearchFields( true ) ? ',' . $this->getFormSearchFields( true ) : '' ) . '));' . "\n";
697                 $js .= $id . '.loadXML(fwUrlAddParams(app_url+app_index_file+"' . $url . '"' . ( $this->getFormSearchFields( true ) ? ',' . $this->getFormSearchFields( true ) : '' ) . '));' . "\n";
698              }else{
699                $js .= $id . '.setXMLAutoLoading(fwUrlAddParams("' . $url . '"' . ( ( $this->getFormSearchFields( true )) ? ',' . $this->getFormSearchFields( true ) : '' ) . '));' . "\n";
700                $js .= $id . '.loadXML(fwUrlAddParams("' . $url . '"' . ( $this->getFormSearchFields( true ) ? ',' . $this->getFormSearchFields( true ) : '' ) . '));' . "\n";
701            }
702        }
703        else
704        {
705            // adicionar os itens orfãos
706            if ( $this->getOrphans() )
707            {
708                foreach( $this->getOrphans() as $k => $item )
709                {
710                    if ( $parent = $this->itens->getElementById( $item->getIdParent() ) )
711                    {
712                        $parent->addItem( $item );
713                    }
714                }
715            }
716            if (is_null($this->itens))
717            {
718                $this->itens = new TTreeViewData( 0, 'root', $expand, '' ); // nivel obrigatório
719            }
720            $js .= $id . ".loadXMLString('" . $this->getXml(false) . "')";
721        }
722        return $js;
723    }
724
725    public function setShowToolBar( $boolNewValue = null )
726    {
727        $this->toolBarVisible = $boolNewValue;
728    }
729
730    public function getShowToolBar()
731    {
732        return is_null( $this->toolBarVisible ) ? true : $this->toolBarVisible;
733        showToolBar;
734    }
735
736    public function showToolBar()
737    {
738        $this->setShowToolBar( true );
739    }
740
741    public function hideToolBar()
742    {
743        $this->setShowToolBar( false );
744    }
745
746    function addOrphan( TTreeViewData $item )
747    {
748        // se existir filhos orfão, adicionar todos os filhos
749        while( $obj = $this->getOrphanByIdParent( $item->getId() ) )
750        {
751            $item->addItem( $obj );
752        }
753
754        // adicionar ao pai se existir
755        if ( $obj = $this->getOrphanById( $item->getIdParent() ) )
756        {
757            $obj->addItem( $item );
758        }
759        else
760        {
761            // adicionar a lista de orfãos
762            $this->arrOrphan[ ] = $item;
763        }
764    }
765
766    function getOrphanById( $strId )
767    {
768        $result = null;
769
770        if ( $this->arrOrphan )
771        {
772            foreach( $this->arrOrphan as $k => $obj )
773            {
774                if ( $obj->getId() == $strId )
775                {
776                    $result = $obj;
777                    break;
778                }
779                //$result = $obj->getOrphanById( $strId );
780            }
781        }
782        return $result;
783    }
784
785    function getOrphanByIdParent( $strId )
786    {
787        $result = null;
788
789        if ( $this->arrOrphan )
790        {
791            foreach( $this->arrOrphan as $k => $obj )
792            {
793                if ( $obj->getIdParent() == $strId )
794                {
795                    $result = $obj;
796                    // remover o registro órfão
797                    array_splice( $this->arrOrphan, $k, 1 );
798                    break;
799                }
800                //$result = $obj->getOrphanByIdParent( $strId );
801            }
802        }
803        return $result;
804    }
805
806    function getOrphans()
807    {
808        return $this->arrOrphan;
809    }
810
811    public function setParentFieldName($strNewValue=null)
812    {
813        $this->parentFieldName = $strNewValue;
814    }
815    public function getParentFieldName()
816    {
817        return $this->parentFieldName;
818    }
819    public function setChildFieldName($strNewValue=null)
820    {
821        $this->childFieldName = $strNewValue;
822    }
823    public function getChildFieldName()
824    {
825        return $this->childFieldName;
826    }
827    public function setDescFieldName($strNewValue=null)
828    {
829        $this->descFieldName = $strNewValue;
830    }
831    public function getDescFieldName()
832    {
833        return $this->descFieldName;
834    }
835    public function setTableName($strNewValue=null)
836    {
837        $this->tableName = $strNewValue;
838    }
839    public function getTableName()
840    {
841        return $this->tableName;
842    }
843    public function setMixData($strNewValue=null)
844    {
845        $this->mixData = $strNewValue;
846    }
847    public function getMixData()
848    {
849        return $this->mixData;
850    }
851    public function setUserDataFieldNames($mixNewValue=null)
852    {
853        $this->userDataFieldNames = $mixNewValue;
854    }
855    public function getUserDataFieldNames()
856    {
857        return $this->userDataFieldNames;
858    }
859    public function getXml($print=false)
860    {
861          if( !$this->itens  )
862        {
863               if( $this->getOrphans() )
864            {
865                list($item) = $this->getOrphans();
866                $this->itens=null;
867                $this->itens = new TTreeViewData( $item->getIdParent(), 'root');
868             }
869            else
870            {
871                $this->itens = new TTreeViewData( $this->getInitialParentKey(), 'root');
872            }
873           }
874           if( $this->getOrphans() )
875           {
876            foreach( $this->getOrphans() as $item )
877            {
878                $this->itens->addItem($item);
879            }
880           }
881
882        $xml = '<?xml version="1.0" encoding="iso-8859-1"?>' . str_replace( chr( 13 ), '', str_replace( chr( 9 ), '', str_replace( chr( 10 ), '', $this->itens->getXml() ) ) );
883        if ( $print === true )
884        {
885            ob_clean();
886            header("Content-type:text/xml");
887            echo $xml;
888        }
889        else
890        {
891            return $xml;
892        }
893    }
894}
895?>