]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarTheme/SugarTheme.php
Release 6.4.0beta1
[Github/sugarcrm.git] / include / SugarTheme / SugarTheme.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39 /*********************************************************************************
40
41  * Description:  Contains a variety of utility functions used to display UI
42  * components such as form headers and footers.  Intended to be modified on a per
43  * theme basis.
44  ********************************************************************************/
45
46 if(!defined('JSMIN_AS_LIB'))
47     define('JSMIN_AS_LIB', true);
48
49 require_once("include/SugarTheme/cssmin.php");
50 require_once("jssource/jsmin.php");
51 require_once('include/utils/sugar_file_utils.php');
52
53 /**
54  * Class that provides tools for working with a theme.
55  */
56 class SugarTheme
57 {
58     /**
59      * Theme name
60      *
61      * @var string
62      */
63     protected $name;
64
65     /**
66      * Theme description
67      *
68      * @var string
69      */
70     protected $description;
71
72     /**
73      * Defines which parent files to not include
74      *
75      * @var string
76      */
77     protected $ignoreParentFiles = array();
78
79     /**
80      * Defines which parent files to not include
81      *
82      * @var string
83      */
84     public $directionality = 'ltr';
85     /**
86      * Theme directory name
87      *
88      * @var string
89      */
90     protected $dirName;
91
92     /**
93      * Parent theme name
94      *
95      * @var string
96      */
97     protected $parentTheme;
98
99     /**
100      * Colors sets provided by the theme
101      *
102      * @deprecated only here for BC during upgrades
103      * @var array
104      */
105     protected $colors = array();
106
107     /**
108      * Font sets provided by the theme
109      *
110      * @deprecated only here for BC during upgrades
111      * @var array
112      */
113     protected $fonts  = array();
114
115     /**
116      * Maximum sugar version this theme is for; defaults to 5.5.1 as all the themes without this
117      * parameter as assumed to work thru 5.5.1
118      *
119      * @var int
120      */
121     protected $version = '5.5.1';
122
123     /**
124      * Colors used in bar charts
125      *
126      * @var array
127      */
128     protected $barChartColors = array(
129         "docBorder"             => "0xffffff",
130         "docBg1"                => "0xffffff",
131         "docBg2"                => "0xffffff",
132         "xText"                 => "0x33485c",
133         "yText"                 => "0x33485c",
134         "title"                 => "0x333333",
135         "misc"                  => "0x999999",
136         "altBorder"             => "0xffffff",
137         "altBg"                 => "0xffffff",
138         "altText"               => "0x666666",
139         "graphBorder"           => "0xcccccc",
140         "graphBg1"              => "0xf6f6f6",
141         "graphBg2"              => "0xf6f6f6",
142         "graphLines"            => "0xcccccc",
143         "graphText"             => "0x333333",
144         "graphTextShadow"       => "0xf9f9f9",
145         "barBorder"             => "0xeeeeee",
146         "barBorderHilite"       => "0x333333",
147         "legendBorder"          => "0xffffff",
148         "legendBg1"             => "0xffffff",
149         "legendBg2"             => "0xffffff",
150         "legendText"            => "0x444444",
151         "legendColorKeyBorder"  => "0x777777",
152         "scrollBar"             => "0xcccccc",
153         "scrollBarBorder"       => "0xeeeeee",
154         "scrollBarTrack"        => "0xeeeeee",
155         "scrollBarTrackBorder"  => "0xcccccc",
156         );
157
158     /**
159      * Colors used in pie charts
160      *
161      * @var array
162      */
163     protected $pieChartColors = array(
164         "docBorder"             => "0xffffff",
165         "docBg1"                => "0xffffff",
166         "docBg2"                => "0xffffff",
167         "title"                 => "0x333333",
168         "subtitle"              => "0x666666",
169         "misc"                  => "0x999999",
170         "altBorder"             => "0xffffff",
171         "altBg"                 => "0xffffff",
172         "altText"               => "0x666666",
173         "graphText"             => "0x33485c",
174         "graphTextShadow"       => "0xf9f9f9",
175         "pieBorder"             => "0xffffff",
176         "pieBorderHilite"       => "0x333333",
177         "legendBorder"          => "0xffffff",
178         "legendBg1"             => "0xffffff",
179         "legendBg2"             => "0xffffff",
180         "legendText"            => "0x444444",
181         "legendColorKeyBorder"  => "0x777777",
182         "scrollBar"             => "0xdfdfdf",
183         "scrollBarBorder"       => "0xfafafa",
184         "scrollBarTrack"        => "0xeeeeee",
185         "scrollBarTrackBorder"  => "0xcccccc",
186         );
187
188     /**
189      * Does this theme support group tabs
190      *
191      * @var bool
192      */
193     public $group_tabs;
194
195
196     /**
197      * Cache built of all css files locations
198      *
199      * @var array
200      */
201     private $_cssCache = array();
202
203     /**
204      * Cache built of all image files locations
205      *
206      * @var array
207      */
208     private $_imageCache = array();
209
210     /**
211      * Cache built of all javascript files locations
212      *
213      * @var array
214      */
215     private $_jsCache = array();
216
217     /**
218      * Cache built of all template files locations
219      *
220      * @var array
221      */
222     private $_templateCache = array();
223
224         /**
225          * Cache built of sprite meta data
226          *
227          * @var array
228          */
229         private $_spriteCache = array();
230
231     /**
232      * Size of the caches after the are initialized in the constructor
233      *
234      * @var array
235      */
236     private $_initialCacheSize = array(
237         'cssCache'      => 0,
238         'imageCache'    => 0,
239         'jsCache'       => 0,
240         'templateCache' => 0,
241                 'spriteCache'   => 0,
242         );
243
244     /**
245      * Controls whether or not to clear the cache on destroy; defaults to false
246      */
247     private $_clearCacheOnDestroy = false;
248
249     private $imageExtensions = array(
250             'gif',
251             'png',
252             'jpg',
253             'tif',
254             'bmp',
255     );
256
257     /**
258      * Constructor
259      *
260      * Sets the theme properties from the defaults passed to it, and loads the file path cache from an external cache
261      *
262      * @param  $defaults string defaults for the current theme
263      */
264     public function __construct(
265         $defaults
266         )
267     {
268         // apply parent theme's properties first
269         if ( isset($defaults['parentTheme']) ) {
270             $themedef = array();
271             include("themes/{$defaults['parentTheme']}/themedef.php");
272             foreach ( $themedef as $key => $value ) {
273                 if ( property_exists(__CLASS__,$key) ) {
274                     // For all arrays ( except colors and fonts ) you can just specify the items
275                     // to change instead of all of the values
276                     if ( is_array($this->$key) && !in_array($key,array('colors','fonts')) )
277                         $this->$key = array_merge($this->$key,$value);
278                     else
279                         $this->$key = $value;
280                 }
281             }
282         }
283         foreach ( $defaults as $key => $value ) {
284             if ( property_exists(__CLASS__,$key) ) {
285                 // For all arrays ( except colors and fonts ) you can just specify the items
286                 // to change instead of all of the values
287                 if ( is_array($this->$key) && !in_array($key,array('colors','fonts')) )
288                     $this->$key = array_merge($this->$key,$value);
289                 else
290                     $this->$key = $value;
291             }
292         }
293         if ( !inDeveloperMode() ) {
294             if ( sugar_is_file($cachedfile = sugar_cached($this->getFilePath().'/pathCache.php'))) {
295                 $caches = unserialize(file_get_contents($cachedfile));
296                 if ( isset($caches['jsCache']) )
297                     $this->_jsCache       = $caches['jsCache'];
298                 if ( isset($caches['cssCache']) )
299                     $this->_cssCache      = $caches['cssCache'];
300                 if ( isset($caches['imageCache']) )
301                     $this->_imageCache    = $caches['imageCache'];
302                 if ( isset($caches['templateCache']) )
303                     $this->_templateCache = $caches['templateCache'];
304             }
305             $cachedfile = sugar_cached($this->getFilePath().'/spriteCache.php');
306                         if(!empty($GLOBALS['sugar_config']['use_sprites']) && sugar_is_file($cachedfile)) {
307                                 $this->_spriteCache = unserialize(sugar_file_get_contents($cachedfile));
308                         }
309         }
310         $this->_initialCacheSize = array(
311             'jsCache'       => count($this->_jsCache),
312             'cssCache'      => count($this->_cssCache),
313             'imageCache'    => count($this->_imageCache),
314             'templateCache' => count($this->_templateCache),
315                         'spriteCache'   => count($this->_spriteCache),
316             );
317     }
318
319     /**
320      * Destructor
321      * Here we'll write out the internal file path caches to an external cache of some sort.
322      */
323     public function __destruct()
324     {
325         // Bug 28309 - Set the current directory to one which we expect it to be (i.e. the root directory of the install
326         set_include_path(realpath(dirname(__FILE__) . '/../..') . PATH_SEPARATOR . get_include_path());
327         $cachedir = sugar_cached($this->getFilePath());
328         if(!file_exists($cachedir)) {
329             sugar_mkdir($cachedir, 0775, true);
330         }
331         // clear out the cache on destroy if we are asked to
332         if ( $this->_clearCacheOnDestroy ) {
333
334             if (is_file("$cachedir/pathCache.php"))
335                 unlink("$cachedir/pathCache.php");
336                         if (is_file("$cachedir/spriteCache.php"))
337                                 unlink("$cachedir/spriteCache.php");
338
339         }
340         elseif ( !inDeveloperMode() ) {
341             // only update the caches if they have been changed in this request
342             if ( count($this->_jsCache) != $this->_initialCacheSize['jsCache']
343                     || count($this->_cssCache) != $this->_initialCacheSize['cssCache']
344                     || count($this->_imageCache) != $this->_initialCacheSize['imageCache']
345                     || count($this->_templateCache) != $this->_initialCacheSize['templateCache']
346                 ) {
347                 sugar_file_put_contents(
348                     "$cachedir/pathCache.php",
349                     serialize(
350                         array(
351                             'jsCache'       => $this->_jsCache,
352                             'cssCache'      => $this->_cssCache,
353                             'imageCache'    => $this->_imageCache,
354                             'templateCache' => $this->_templateCache,
355                             )
356                         )
357                     );
358
359             }
360                         if ( count($this->_spriteCache) != $this->_initialCacheSize['spriteCache']) {
361                                 sugar_file_put_contents(
362                                         "$cachedir/spriteCache.php",
363                                         serialize($this->_spriteCache)
364                                 );
365                         }
366         }
367     }
368
369     /**
370      * Specifies what is returned when the object is cast to a string, in this case it will be the
371      * theme directory name.
372      *
373      * @return string theme directory name
374      */
375     public function __toString()
376     {
377         return $this->dirName;
378     }
379
380     /**
381      * Generic public accessor method for all the properties of the theme ( which are kept protected )
382      *
383      * @return string
384      */
385     public function __get(
386         $key
387         )
388     {
389         if ( isset($this->$key) )
390             return $this->$key;
391     }
392
393     public function __isset($key){
394         return isset($this->$key);
395
396     }
397
398     public function clearJSCache()
399     {
400         $this->_jsCache = array();
401     }
402
403     /**
404      * Clears out the caches used for this themes
405      */
406     public function clearCache()
407     {
408         $this->_clearCacheOnDestroy = true;
409     }
410
411     /**
412      * Return array of all valid fields that can be specified in the themedef.php file
413      *
414      * @return array
415      */
416     public static function getThemeDefFields()
417     {
418         return array(
419             'name',
420             'description',
421             'directionality',
422             'dirName',
423             'parentTheme',
424             'version',
425             'colors',
426             'fonts',
427             'barChartColors',
428             'pieChartColors',
429             'group_tabs',
430             'ignoreParentFiles',
431             );
432     }
433
434     /**
435      * Returns the file path of the current theme
436      *
437      * @return string
438      */
439     public function getFilePath()
440     {
441         return 'themes/'.$this->dirName;
442     }
443
444     /**
445      * Returns the image path of the current theme
446      *
447      * @return string
448      */
449     public function getImagePath()
450     {
451         return $this->getFilePath().'/images';
452     }
453
454     /**
455      * Returns the css path of the current theme
456      *
457      * @return string
458      */
459     public function getCSSPath()
460     {
461         return $this->getFilePath().'/css';
462     }
463
464     /**
465      * Returns the javascript path of the current theme
466      *
467      * @return string
468      */
469     public function getJSPath()
470     {
471         return $this->getFilePath().'/js';
472     }
473
474     /**
475      * Returns the tpl path of the current theme
476      *
477      * @return string
478      */
479     public function getTemplatePath()
480     {
481         return $this->getFilePath().'/tpls';
482     }
483
484     /**
485      * Returns the file path of the theme defaults
486      *
487      * @return string
488      */
489     public final function getDefaultFilePath()
490     {
491         return 'themes/default';
492     }
493
494     /**
495      * Returns the image path of the theme defaults
496      *
497      * @return string
498      */
499     public final function getDefaultImagePath()
500     {
501         return $this->getDefaultFilePath().'/images';
502     }
503
504     /**
505      * Returns the css path of the theme defaults
506      *
507      * @return string
508      */
509     public final function getDefaultCSSPath()
510     {
511         return $this->getDefaultFilePath().'/css';
512     }
513
514     /**
515      * Returns the template path of the theme defaults
516      *
517      * @return string
518      */
519     public final function getDefaultTemplatePath()
520     {
521         return $this->getDefaultFilePath().'/tpls';
522     }
523
524     /**
525      * Returns the javascript path of the theme defaults
526      *
527      * @return string
528      */
529     public final function getDefaultJSPath()
530     {
531         return $this->getDefaultFilePath().'/js';
532     }
533
534     /**
535      * Returns CSS for the current theme.
536      *
537      * @param  $color string optional, specifies the css color file to use if the theme supports it; defaults to cookie value or theme default
538      * @param  $font  string optional, specifies the css font file to use if the theme supports it; defaults to cookie value or theme default
539      * @return string HTML code
540      */
541     public function getCSS(
542         $color = null,
543         $font = null
544         )
545     {
546         // include style.css file
547         $html = '<link rel="stylesheet" type="text/css" href="'.$this->getCSSURL('yui.css').'" />';
548         $html .= '<link rel="stylesheet" type="text/css" href="'.$this->getCSSURL('deprecated.css').'" />';
549         $html .= '<link rel="stylesheet" type="text/css" href="'.$this->getCSSURL('style.css').'" />';
550
551                 // sprites
552                 if(!empty($GLOBALS['sugar_config']['use_sprites']) && $GLOBALS['sugar_config']['use_sprites']) {
553
554                         // system wide sprites
555                         if(file_exists("cache/sprites/default/sprites.css"))
556                                 $html .= '<link rel="stylesheet" type="text/css" href="cache/sprites/default/sprites.css" />';
557
558                         // theme specific sprites
559                         if(file_exists("cache/sprites/{$this->dirName}/sprites.css"))
560                                 $html .= '<link rel="stylesheet" type="text/css" href="cache/sprites/'.$this->dirName.'/sprites.css" />';
561
562                         // parent sprites
563                         if($this->parentTheme && $parent = SugarThemeRegistry::get($this->parentTheme)) {
564                                 if(file_exists("cache/sprites/{$parent->dirName}/sprites.css"))
565                                         $html .= '<link rel="stylesheet" type="text/css" href="cache/sprites/'.$parent->dirName.'/sprites.css" />';
566                         }
567
568                         // repeatable sprites
569                         if(file_exists("cache/sprites/Repeatable/sprites.css"))
570                                 $html .= '<link rel="stylesheet" type="text/css" href="cache/sprites/Repeatable/sprites.css" />';
571                 }
572
573         // for BC during upgrade
574         if ( !empty($this->colors) ) {
575             if ( isset($_SESSION['authenticated_user_theme_color']) && in_array($_SESSION['authenticated_user_theme_color'], $this->colors))
576                 $color = $_SESSION['authenticated_user_theme_color'];
577             else
578                 $color = $this->colors[0];
579             $html .= '<link rel="stylesheet" type="text/css" href="'.$this->getCSSURL('colors.'.$color.'.css').'" id="current_color_style" />';
580         }
581
582         if ( !empty($this->fonts) ) {
583             if ( isset($_SESSION['authenticated_user_theme_font']) && in_array($_SESSION['authenticated_user_theme_font'], $this->fonts))
584                 $font = $_SESSION['authenticated_user_theme_font'];
585             else
586                 $font = $this->fonts[0];
587             $html .= '<link rel="stylesheet" type="text/css" href="'.$this->getCSSURL('fonts.'.$font.'.css').'" id="current_font_style" />';
588         }
589
590         return $html;
591     }
592
593     /**
594      * Returns javascript for the current theme
595      *
596      * @return string HTML code
597      */
598     public function getJS()
599     {
600         $styleJS = $this->getJSURL('style.js');
601         return <<<EOHTML
602 <script type="text/javascript" src="$styleJS"></script>
603 EOHTML;
604     }
605
606     /**
607      * Returns the path for the tpl file in the current theme. If not found in the current theme, will revert
608      * to looking in the base theme.
609      *
610      * @param  string $templateName tpl file name
611      * @return string path of tpl file to include
612      */
613     public function getTemplate(
614         $templateName
615         )
616     {
617         if ( isset($this->_templateCache[$templateName]) )
618             return $this->_templateCache[$templateName];
619
620         $templatePath = '';
621         if (sugar_is_file('custom/'.$this->getTemplatePath().'/'.$templateName))
622             $templatePath = 'custom/'.$this->getTemplatePath().'/'.$templateName;
623         elseif (sugar_is_file($this->getTemplatePath().'/'.$templateName))
624             $templatePath = $this->getTemplatePath().'/'.$templateName;
625         elseif (isset($this->parentTheme)
626                 && SugarThemeRegistry::get($this->parentTheme) instanceOf SugarTheme
627                 && ($filename = SugarThemeRegistry::get($this->parentTheme)->getTemplate($templateName)) != '')
628             $templatePath = $filename;
629         elseif (sugar_is_file('custom/'.$this->getDefaultTemplatePath().'/'.$templateName))
630             $templatePath = 'custom/'.$this->getDefaultTemplatePath().'/'.$templateName;
631         elseif (sugar_is_file($this->getDefaultTemplatePath().'/'.$templateName))
632             $templatePath = $this->getDefaultTemplatePath().'/'.$templateName;
633         else {
634             $GLOBALS['log']->warn("Template $templateName not found");
635             return false;
636         }
637
638         $this->_imageCache[$templateName] = $templatePath;
639
640         return $templatePath;
641     }
642
643     /**
644      * Returns an image tag for the given image.
645      *
646      * @param  string $image image name
647      * @param  string $other_attributes optional, other attributes to add to the image tag, not cached
648          * @param  string $width optional, defaults to the actual image's width
649          * @param  string $height optional, defaults to the actual image's height
650          * @param  string $ext optional, image extension (TODO can we depricate this one ?)
651      * @param  string $alt optional, only used when image contains something useful, i.e. "Sally's profile pic"
652      * @return string HTML image tag or sprite
653      */
654     public function getImage(
655         $imageName,
656         $other_attributes = '',
657                 $width = null,
658                 $height = null,
659                 $ext = null,
660         $alt = ''
661     )
662     {
663
664         static $cached_results = array();
665
666                 // trap depricated use of image extension
667                 if(is_null($ext)) {
668                         $imageNameExp = explode('.',$imageName);
669                         if(count($imageNameExp) == 1)
670                                 $imageName .= '.gif';
671                 } else {
672                         $imageName .= $ext;
673                 }
674
675                 // trap alt attributes in other_attributes
676                 if(preg_match('/alt=["\']([^\'"]+)["\']/i', $other_attributes))
677                         $GLOBALS['log']->debug("VINK alt attribute detected for $imageName");
678
679                 // sprite handler, makes use of own caching mechanism
680                 if(!empty($GLOBALS['sugar_config']['use_sprites']) && $GLOBALS['sugar_config']['use_sprites']) {
681                         // get sprite metadata
682                         if($sp = $this->getSpriteMeta($imageName)) {
683                                 // requested size should match
684                                 if( (!is_null($width) && $sp['width'] == $width) || (is_null($width)) &&
685                                         (!is_null($height) && $sp['height'] == $height) || (is_null($height)) )
686                                 {
687                                         if($sprite = $this->getSprite($sp['class'], $other_attributes, $alt))
688                                                 return $sprite;
689                                 }
690                         }
691                 }
692
693                 // img caching
694                 if(empty($cached_results[$imageName])) {
695                         $imageURL = $this->getImageURL($imageName,false);
696                         if ( empty($imageURL) )
697                                 return false;
698                 $cached_results[$imageName] = '<img src="'.getJSPath($imageURL).'" ';
699                 }
700
701                 $attr_width = (is_null($width)) ? "" : "width=\"$width\"";
702                 $attr_height = (is_null($height)) ? "" : "height=\"$height\"";
703                 return $cached_results[$imageName] . " $attr_width $attr_height $other_attributes alt=\"$alt\" />";
704     }
705
706         /**
707          * Returns sprite meta data
708          *
709          * @param  string $imageName Image filename including extension
710          * @return array  Sprite meta data
711          */
712         public function getSpriteMeta($imageName) {
713
714                 // return from cache
715                 if(isset($this->_spriteCache[$imageName]))
716                         return $this->_spriteCache[$imageName];
717
718                 // sprite keys are base on imageURL
719                 $imageURL = $this->getImageURL($imageName,false);
720                 if(empty($imageURL)) {
721                         $this->_spriteCache[$imageName] = false;
722                         return false;
723                 }
724
725                 // load meta data, includes default images
726                 require_once("include/SugarTheme/SugarSprites.php");
727                 $meta = SugarSprites::getInstance();
728
729                 // add current theme dir
730                 $meta->loadSpriteMeta($this->dirName);
731                 // add parent theme dir
732                 if($this->parentTheme && $parent = SugarThemeRegistry::get($this->parentTheme)) {
733                         $meta->loadSpriteMeta($parent->dirName);
734                 }
735
736                 // add to cache
737                 if(isset($meta->sprites[$imageURL])) {
738                         $this->_spriteCache[$imageName] = $meta->sprites[$imageURL];
739                         // add imageURL to cache
740                         //$this->_spriteCache[$imageName]['imageURL'] = $imageURL;
741                 } else {
742                         $this->_spriteCache[$imageName] = false;
743                         $GLOBALS['log']->debug("VINK sprite miss for $imageURL");
744                 }
745                 return $this->_spriteCache[$imageName];
746         }
747
748         /**
749          * Returns sprite HTML span tag
750          *
751          * @param  string class The md5 id used in the CSS sprites class
752          * @param  string attr  optional, list of additional html attributes
753          * @param  string title optional, the title (equivalent to alt on img)
754          * @return string HTML span tag
755          */
756         public function getSprite($class, $attr, $title) {
757
758                 // handle multiple class tags
759                 $class_regex = '/class=["\']([^\'"]+)["\']/i';
760                 preg_match($class_regex, $attr, $match);
761                 if(isset($match[1])) {
762                         $attr = preg_replace($class_regex, 'class="spr_'.$class.' ${1}"', $attr);
763
764                 // single class
765                 } else {
766                         $attr .= ' class="spr_'.$class.'"';
767                 }
768
769                 if($title)
770                         $attr .= ' title="'.$title.'"';
771
772                 // use </span> instead of /> to prevent weird UI results
773                 $GLOBALS['log']->debug("VINK generated sprite -> $attr");
774                 return "<span {$attr}></span>";
775         }
776
777         /**
778          * Returns a link HTML tag with or without an embedded image
779          */
780     public function getLink(
781                 $url,
782                 $title,
783                 $other_attributes = '',
784         $img_name = '',
785         $img_other_attributes = '',
786                 $img_width = null,
787                 $img_height = null,
788                 $img_alt = '',
789                 $img_placement = 'imageonly'
790     )
791     {
792
793                 if($img_name) {
794                         $img = $this->getImage($img_name, $img_other_attributes, $img_width, $img_height, null, $img_alt);
795                         if($img == false) {
796                                 $GLOBALS['log']->debug('VINK unknown image getLink');
797                                 $img = 'unknown';
798                         }
799                         switch($img_placement) {
800                                 case 'left':    $inner_html = $img.$title; break;
801                                 case 'right':   $inner_html = $title.$img; break;
802                                 default:                $inner_html = $img; break;
803                         }
804                 } else {
805                         $inner_html = $title;
806                 }
807
808                 return '<a href="'.$url.'" title="'.$title.'" '.$other_attributes.'>'.$inner_html.'</a>';
809
810         }
811
812     /**
813      * Returns the URL for an image in the current theme. If not found in the current theme, will revert
814      * to looking in the base theme.
815      * @param  string $imageName image file name
816      * @param  bool   $addJSPath call getJSPath() with the results to add some unique image tracking support
817      * @return string path to image
818      */
819     public function getImageURL(
820         $imageName,
821         $addJSPath = true
822         ){
823         if ( isset($this->_imageCache[$imageName]) ) {
824             if ( $addJSPath )
825                 return getJSPath($this->_imageCache[$imageName]);
826             else
827                 return $this->_imageCache[$imageName];
828         }
829         $imagePath = '';
830         if (($filename = $this->_getImageFileName('custom/'.$this->getImagePath().'/'.$imageName)) != '')
831             $imagePath = $filename;
832         elseif (($filename = $this->_getImageFileName($this->getImagePath().'/'.$imageName)) != '')
833             $imagePath = $filename;
834         elseif (isset($this->parentTheme)
835                 && SugarThemeRegistry::get($this->parentTheme) instanceOf SugarTheme
836                 && ($filename = SugarThemeRegistry::get($this->parentTheme)->getImageURL($imageName,false)) != '')
837             $imagePath = $filename;
838         elseif (($filename = $this->_getImageFileName('custom/'.$this->getDefaultImagePath().'/'.$imageName)) != '')
839             $imagePath = $filename;
840         elseif (($filename = $this->_getImageFileName($this->getDefaultImagePath().'/'.$imageName)) != '')
841             $imagePath = $filename;
842                 elseif (($filename = $this->_getImageFileName('include/images/'.$imageName)) != '')
843                         $imagePath = $filename;
844         else {
845             $GLOBALS['log']->warn("Image $imageName not found");
846             return false;
847         }
848
849         $this->_imageCache[$imageName] = $imagePath;
850
851         if ( $addJSPath )
852             return getJSPath($imagePath);
853
854         return $imagePath;
855     }
856
857     /**
858      * Checks for an image using all of the accepted image extensions
859      *
860      * @param  string $imageName image file name
861      * @return string path to image
862      */
863     protected function _getImageFileName(
864         $imageName
865         )
866     {
867         // return now if the extension matches that of which we are looking for
868         if ( sugar_is_file($imageName) )
869             return $imageName;
870         $pathParts = pathinfo($imageName);
871         foreach ( $this->imageExtensions as $extension )
872             if ( isset($pathParts['extension']) )
873                 if ( ( $extension != $pathParts['extension'] )
874                         && sugar_is_file($pathParts['dirname'].'/'.$pathParts['filename'].'.'.$extension) )
875                     return $pathParts['dirname'].'/'.$pathParts['filename'].'.'.$extension;
876
877         return '';
878     }
879
880     /**
881      * Returns the URL for the css file in the current theme. If not found in the current theme, will revert
882      * to looking in the base theme.
883      *
884      * @param  string $cssFileName css file name
885      * @param  bool   $returnURL if true, returns URL with unique image mark, otherwise returns path to the file
886      * @return string path of css file to include
887      */
888     public function getCSSURL($cssFileName, $returnURL = true)
889     {
890         if ( isset($this->_cssCache[$cssFileName]) && sugar_is_file(sugar_cached($this->_cssCache[$cssFileName])) ) {
891             if ( $returnURL )
892                 return getJSPath("cache/".$this->_cssCache[$cssFileName]);
893             else
894                 return sugar_cached($this->_cssCache[$cssFileName]);
895         }
896
897         $cssFileContents = '';
898         $defaultFileName = $this->getDefaultCSSPath().'/'.$cssFileName;
899         $fullFileName = $this->getCSSPath().'/'.$cssFileName;
900         if (isset($this->parentTheme)
901                 && SugarThemeRegistry::get($this->parentTheme) instanceOf SugarTheme
902                 && ($filename = SugarThemeRegistry::get($this->parentTheme)->getCSSURL($cssFileName,false)) != '')
903             $cssFileContents .= file_get_contents($filename);
904         else {
905             if (sugar_is_file($defaultFileName))
906                 $cssFileContents .= file_get_contents($defaultFileName);
907             if (sugar_is_file('custom/'.$defaultFileName))
908                 $cssFileContents .= file_get_contents('custom/'.$defaultFileName);
909         }
910         if (sugar_is_file($fullFileName)) {
911             $cssFileContents .= file_get_contents($fullFileName);
912         }
913         if (sugar_is_file('custom/'.$fullFileName)) {
914             $cssFileContents .= file_get_contents('custom/'.$fullFileName);
915         }
916         if (empty($cssFileContents)) {
917             $GLOBALS['log']->warn("CSS File $cssFileName not found");
918             return false;
919         }
920
921         // fix any image references that may be defined in css files
922         $cssFileContents = str_ireplace("entryPoint=getImage&",
923             "entryPoint=getImage&themeName={$this->dirName}&",
924             $cssFileContents);
925
926         // create the cached file location
927         $cssFilePath = create_cache_directory($fullFileName);
928
929         // if this is the style.css file, prepend the base.css and calendar-win2k-cold-1.css
930         // files before the theme styles
931         if ( $cssFileName == 'style.css' && !isset($this->parentTheme) ) {
932             if ( inDeveloperMode() )
933                 $cssFileContents = file_get_contents('include/javascript/yui/build/base/base.css') . $cssFileContents;
934             else
935                 $cssFileContents = file_get_contents('include/javascript/yui/build/base/base-min.css') . $cssFileContents;
936         }
937
938         // minify the css
939         if ( !inDeveloperMode() && !sugar_is_file($cssFilePath) ) {
940             $cssFileContents = cssmin::minify($cssFileContents);
941         }
942
943         // now write the css to cache
944         sugar_file_put_contents($cssFilePath,$cssFileContents);
945
946         $this->_cssCache[$cssFileName] = $fullFileName;
947
948         if ( $returnURL )
949             return getJSPath("cache/".$fullFileName);
950
951         return sugar_cached($fullFileName);
952     }
953
954     /**
955      * Returns the URL for an image in the current theme. If not found in the current theme, will revert
956      * to looking in the base theme.
957      *
958      * @param  string $jsFileName js file name
959      * @param  bool   $returnURL if true, returns URL with unique image mark, otherwise returns path to the file
960      * @return string path to js file
961      */
962     public function getJSURL($jsFileName, $returnURL = true)
963     {
964         if ( isset($this->_jsCache[$jsFileName]) && sugar_is_file(sugar_cached($this->_jsCache[$jsFileName])) ) {
965             if ( $returnURL )
966                 return getJSPath("cache/".$this->_jsCache[$jsFileName]);
967             else
968                 return sugar_cached($this->_jsCache[$jsFileName]);
969         }
970
971         $jsFileContents = '';
972         $fullFileName = $this->getJSPath().'/'.$jsFileName;
973         $defaultFileName = $this->getDefaultJSPath().'/'.$jsFileName;
974         if (isset($this->parentTheme)
975                 && SugarThemeRegistry::get($this->parentTheme) instanceOf SugarTheme
976                 && ($filename = SugarThemeRegistry::get($this->parentTheme)->getJSURL($jsFileName,false)) != '') {
977            $jsFileContents .= file_get_contents($filename);
978        } else {
979             if (sugar_is_file($defaultFileName))
980                 $jsFileContents .= file_get_contents($defaultFileName);
981             if (sugar_is_file('custom/'.$defaultFileName))
982                 $jsFileContents .= file_get_contents('custom/'.$defaultFileName);
983         }
984         if (sugar_is_file($fullFileName))
985             $jsFileContents .= file_get_contents($fullFileName);
986         if (sugar_is_file('custom/'.$fullFileName))
987             $jsFileContents .= file_get_contents('custom/'.$fullFileName);
988         if (empty($jsFileContents)) {
989             $GLOBALS['log']->warn("Javascript File $jsFileName not found");
990             return false;
991         }
992
993         // create the cached file location
994         $jsFilePath = create_cache_directory($fullFileName);
995
996         // minify the js
997         if ( !inDeveloperMode()&& !sugar_is_file(str_replace('.js','-min.js',$jsFilePath)) ) {
998             $jsFileContents = JSMin::minify($jsFileContents);
999             $jsFilePath = str_replace('.js','-min.js',$jsFilePath);
1000             $fullFileName = str_replace('.js','-min.js',$fullFileName);
1001         }
1002
1003         // now write the js to cache
1004         sugar_file_put_contents($jsFilePath,$jsFileContents);
1005
1006         $this->_jsCache[$jsFileName] = $fullFileName;
1007
1008         if ( $returnURL )
1009             return getJSPath("cache/".$fullFileName);
1010
1011         return sugar_cached($fullFileName);
1012     }
1013
1014     /**
1015      * Returns an array of all of the images available for the current theme
1016      *
1017      * @return array
1018      */
1019     public function getAllImages()
1020     {
1021         // first, lets get all the paths of where to look
1022         $pathsToSearch = array($this->getImagePath());
1023         $theme = $this;
1024         while (isset($theme->parentTheme) && SugarThemeRegistry::get($theme->parentTheme) instanceOf SugarTheme ) {
1025             $theme = SugarThemeRegistry::get($theme->parentTheme);
1026             $pathsToSearch[] = $theme->getImagePath();
1027         }
1028         $pathsToSearch[] = $this->getDefaultImagePath();
1029
1030         // now build the array
1031         $imageArray = array();
1032         foreach ( $pathsToSearch as $path )
1033         {
1034             if (!sugar_is_dir($path)) $path = "custom/$path";
1035             if (sugar_is_dir($path) && is_readable($path) && $dir = opendir($path)) {
1036                 while (($file = readdir($dir)) !== false) {
1037                     if ($file == ".."
1038                             || $file == "."
1039                             || $file == ".svn"
1040                             || $file == "CVS"
1041                             || $file == "Attic"
1042                             )
1043                         continue;
1044                     if ( !isset($imageArray[$file]) )
1045                         $imageArray[$file] = $this->getImageURL($file,false);
1046                 }
1047                 closedir($dir);
1048             }
1049         }
1050
1051         ksort($imageArray);
1052
1053         return $imageArray;
1054     }
1055
1056 }
1057
1058 /**
1059  * Registry for all the current classes in the system
1060  */
1061 class SugarThemeRegistry
1062 {
1063     /**
1064      * Array of all themes and thier object
1065      *
1066      * @var array
1067      */
1068     private static $_themes = array();
1069
1070     /**
1071      * Name of the current theme; corresponds to an index key in SugarThemeRegistry::$_themes
1072      *
1073      * @var string
1074      */
1075     private static $_currentTheme;
1076
1077     /**
1078      * Disable the constructor since this will be a singleton
1079      */
1080     private function __construct() {}
1081
1082     /**
1083      * Adds a new theme to the registry
1084      *
1085      * @param $themedef array
1086      */
1087     public static function add(
1088         array $themedef
1089         )
1090     {
1091         // make sure the we know the sugar version
1092         if ( !isset($GLOBALS['sugar_version']) ) {
1093             include('sugar_version.php');
1094             $GLOBALS['sugar_version'] = $sugar_version;
1095         }
1096
1097         // Assume theme is designed for 5.5.x if not specified otherwise
1098         if ( !isset($themedef['version']) )
1099             $themedef['version']['regex_matches'] = array('5\.5\.*');
1100
1101         // Check to see if theme is valid for this version of Sugar; return false if not
1102         $version_ok = false;
1103         if( isset($themedef['version']['exact_matches']) ){
1104             $matches_empty = false;
1105             foreach( $themedef['version']['exact_matches'] as $match ){
1106                 if( $match == $GLOBALS['sugar_version'] ){
1107                     $version_ok = true;
1108                 }
1109             }
1110         }
1111         if( !$version_ok && isset($themedef['version']['regex_matches']) ){
1112             $matches_empty = false;
1113             foreach( $themedef['version']['regex_matches'] as $match ){
1114                 if( preg_match( "/$match/", $GLOBALS['sugar_version'] ) ){
1115                     $version_ok = true;
1116                 }
1117             }
1118         }
1119         if ( !$version_ok )
1120             return false;
1121
1122         $theme = new SugarTheme($themedef);
1123         self::$_themes[$theme->dirName] = $theme;
1124     }
1125
1126     /**
1127      * Removes a new theme from the registry
1128      *
1129      * @param $themeName string
1130      */
1131     public static function remove(
1132         $themeName
1133         )
1134     {
1135         if ( self::exists($themeName) )
1136             unset(self::$_themes[$themeName]);
1137     }
1138
1139     /**
1140      * Returns a theme object in the registry specified by the given $themeName
1141      *
1142      * @param $themeName string
1143      */
1144     public static function get(
1145         $themeName
1146         )
1147     {
1148         if ( isset(self::$_themes[$themeName]) )
1149             return self::$_themes[$themeName];
1150     }
1151
1152     /**
1153      * Returns the current theme object
1154      *
1155      * @return SugarTheme object
1156      */
1157     public static function current()
1158     {
1159         if ( !isset(self::$_currentTheme) )
1160             self::buildRegistry();
1161
1162         return self::$_themes[self::$_currentTheme];
1163     }
1164
1165     /**
1166      * Returns the default theme object
1167      *
1168      * @return SugarTheme object
1169      */
1170     public static function getDefault()
1171     {
1172         if ( !isset(self::$_currentTheme) )
1173             self::buildRegistry();
1174
1175         if ( isset($GLOBALS['sugar_config']['default_theme']) && self::exists($GLOBALS['sugar_config']['default_theme']) ) {
1176             return self::get($GLOBALS['sugar_config']['default_theme']);
1177         }
1178
1179         return self::get(array_pop(array_keys(self::availableThemes())));
1180     }
1181
1182     /**
1183      * Returns true if a theme object specified by the given $themeName exists in the registry
1184      *
1185      * @param  $themeName string
1186      * @return bool
1187      */
1188     public static function exists(
1189         $themeName
1190         )
1191     {
1192         return (self::get($themeName) !== null);
1193     }
1194
1195     /**
1196      * Sets the given $themeName to be the current theme
1197      *
1198      * @param  $themeName string
1199      */
1200     public static function set(
1201         $themeName
1202         )
1203     {
1204         if ( !self::exists($themeName) )
1205             return false;
1206
1207         self::$_currentTheme = $themeName;
1208
1209         // set some of the expected globals
1210         $GLOBALS['barChartColors'] = self::current()->barChartColors;
1211         $GLOBALS['pieChartColors'] = self::current()->pieChartColors;
1212         return true;
1213     }
1214
1215     /**
1216      * Builds the theme registry
1217      */
1218     public static function buildRegistry()
1219     {
1220         self::$_themes = array();
1221         $dirs = array("themes/","custom/themes/");
1222
1223         // check for a default themedef file
1224         $themedefDefault = array();
1225         if ( sugar_is_file("custom/themes/default/themedef.php") ) {
1226             $themedef = array();
1227             require("custom/themes/default/themedef.php");
1228             $themedefDefault = $themedef;
1229         }
1230
1231         foreach ($dirs as $dirPath ) {
1232             if (sugar_is_dir('./'.$dirPath) && is_readable('./'.$dirPath) && $dir = opendir('./'.$dirPath)) {
1233                 while (($file = readdir($dir)) !== false) {
1234                     if ($file == ".."
1235                             || $file == "."
1236                             || $file == ".svn"
1237                             || $file == "CVS"
1238                             || $file == "Attic"
1239                             || $file == "default"
1240                             || !sugar_is_dir("./$dirPath".$file)
1241                             || !sugar_is_file("./{$dirPath}{$file}/themedef.php")
1242                             )
1243                         continue;
1244                     $themedef = array();
1245                     require("./{$dirPath}{$file}/themedef.php");
1246                     $themedef = array_merge($themedef,$themedefDefault);
1247                     $themedef['dirName'] = $file;
1248                     // check for theme already existing in the registry
1249                     // if so, then it will override the current one
1250                     if ( self::exists($themedef['dirName']) ) {
1251                         $existingTheme = self::get($themedef['dirName']);
1252                         foreach ( SugarTheme::getThemeDefFields() as $field )
1253                             if ( !isset($themedef[$field]) )
1254                                 $themedef[$field] = $existingTheme->$field;
1255                         self::remove($themedef['dirName']);
1256                     }
1257                     if ( isset($themedef['name']) ) {
1258                         self::add($themedef);
1259                     }
1260                 }
1261                 closedir($dir);
1262             }
1263         }
1264         // default to setting the default theme as the current theme
1265         if ( !isset($GLOBALS['sugar_config']['default_theme']) || !self::set($GLOBALS['sugar_config']['default_theme']) ) {
1266             if ( count(self::availableThemes()) == 0 )
1267                 sugar_die('No valid themes are found on this instance');
1268             else
1269                 self::set(array_pop(array_keys(self::availableThemes())));
1270         }
1271     }
1272
1273     /**
1274      * Returns an array of available themes. Designed to be absorbed into get_select_options_with_id()
1275      *
1276      * @return array
1277      */
1278     public static function availableThemes()
1279     {
1280         $themelist = array();
1281         $disabledThemes = array();
1282         if ( isset($GLOBALS['sugar_config']['disabled_themes']) )
1283             $disabledThemes = explode(',',$GLOBALS['sugar_config']['disabled_themes']);
1284
1285         foreach ( self::$_themes as $themename => $themeobject ) {
1286             if ( in_array($themename,$disabledThemes) )
1287                 continue;
1288             $themelist[$themeobject->dirName] = $themeobject->name;
1289         }
1290         asort($themelist, SORT_STRING);
1291         return $themelist;
1292     }
1293
1294     /**
1295      * Returns an array of un-available themes. Designed used with the theme selector in the admin panel
1296      *
1297      * @return array
1298      */
1299     public static function unAvailableThemes()
1300     {
1301         $themelist = array();
1302         $disabledThemes = array();
1303         if ( isset($GLOBALS['sugar_config']['disabled_themes']) )
1304             $disabledThemes = explode(',',$GLOBALS['sugar_config']['disabled_themes']);
1305
1306         foreach ( self::$_themes as $themename => $themeobject ) {
1307             if ( in_array($themename,$disabledThemes) )
1308                 $themelist[$themeobject->dirName] = $themeobject->name;
1309         }
1310
1311         return $themelist;
1312     }
1313
1314     /**
1315      * Returns an array of all themes found in the current installation
1316      *
1317      * @return array
1318      */
1319     public static function allThemes()
1320     {
1321         $themelist = array();
1322
1323         foreach ( self::$_themes as $themename => $themeobject )
1324             $themelist[$themeobject->dirName] = $themeobject->name;
1325
1326         return $themelist;
1327     }
1328
1329     /**
1330      * Clears out the cached path locations for all themes
1331      */
1332     public static function clearAllCaches()
1333     {
1334         foreach ( self::$_themes as $themeobject ) {
1335             $themeobject->clearCache();
1336         }
1337     }
1338 }