Overview

Packages

  • application
    • commands
    • components
      • actions
      • filters
      • leftWidget
      • permissions
      • sortableWidget
      • util
      • webupdater
      • x2flow
        • actions
        • triggers
      • X2GridView
      • X2Settings
    • controllers
    • models
      • embedded
    • modules
      • accounts
        • controllers
        • models
      • actions
        • controllers
        • models
      • calendar
        • controllers
        • models
      • charts
        • models
      • contacts
        • controllers
        • models
      • docs
        • components
        • controllers
        • models
      • groups
        • controllers
        • models
      • marketing
        • components
        • controllers
        • models
      • media
        • controllers
        • models
      • mobile
        • components
      • opportunities
        • controllers
        • models
      • products
        • controllers
        • models
      • quotes
        • controllers
        • models
      • services
        • controllers
        • models
      • template
        • models
      • users
        • controllers
        • models
      • workflow
        • controllers
        • models
      • x2Leads
        • controllers
        • models
  • None
  • system
    • base
    • caching
    • console
    • db
      • ar
      • schema
    • validators
    • web
      • actions
      • auth
      • helpers
      • widgets
        • captcha
        • pagers
  • zii
    • widgets
      • grid

Classes

  • ActionFormModel
  • ArrayUtil
  • ArrayValidator
  • AssociatedMediaBehavior
  • AuxLib
  • Changelog
  • DetailView
  • EncryptUtilTmp
  • EventsWidgetFieldFormatter
  • FailedLogins
  • FieldFormatter
  • FieldFormatterBase
  • FieldInputRenderer
  • FileFieldBehavior
  • FiltersForm
  • FilterUtil
  • FineDiff
  • FineDiffCopyOp
  • FineDiffDeleteOp
  • FineDiffInsertOp
  • FineDiffOp
  • FineDiffOps
  • FineDiffReplaceOp
  • GlobalCSSFormModel
  • GlobalImportFormModel
  • GoogleAuthenticator
  • JSONFieldsBehavior
  • JSONResponse
  • MediaFieldFormatter
  • MediaSelector
  • MobileActiveRecordFieldFormatter
  • MobileActivityFeed
  • MobileChartDashboard
  • MobileFieldFormatter
  • MobileFieldInputRenderer
  • ModuleModelNameValidator
  • MultiChildNode
  • MultiTypeAutocomplete
  • PasswordUtil
  • ProductFeature
  • ProfileWidgetLayout
  • QueryParamGenerator
  • RecordLimitBehavior
  • RecordView
  • RecordViewWidgetLayout
  • RelationshipsGridModel
  • RelationshipsJoin
  • RepairUserDataCommand
  • RequestUtil
  • RequiredIfNotSetValidator
  • ResponseUtil
  • RunMigrationScriptCommand
  • ServiceWebFormDesigner
  • Settings
  • StringUtil
  • TestEmailAction
  • TestEmailActionForm
  • ThemeGenerator
  • TimerUtil
  • TopicsFieldFormatter
  • TopicsWidgetLayout
  • TransactionalViewFieldFormatter
  • UrlUtil
  • ValidLinkValidator
  • WebFormDesigner
  • WebLeadFormDesigner
  • X2ActiveRecordBehavior
  • X2ActiveRecordFieldFormatter
  • X2ButtonColumn
  • X2ConditionList
  • X2ConsoleCommand
  • X2ControllerBehavior
  • X2DataColumn
  • X2DuplicateBehavior
  • X2Flashes
  • X2GridViewFieldFormatter
  • X2IPAddress
  • X2LeadsDataColumn
  • X2MergeableBehavior
  • X2MessageSource
  • X2MobileControllerBehavior
  • X2MobileProfileControllerBehavior
  • X2MobileQuotesControllerBehavior
  • X2MobileSiteControllerBehavior
  • X2MobileTopicsControllerBehavior
  • X2ModelConversionBehavior
  • X2ModelConversionWidget
  • X2ModelForeignKeyValidator
  • X2ModelUniqueIndexValidator
  • X2NonWebUser
  • X2StaticDropdown
  • X2StaticField
  • X2StaticFieldsBehavior
  • X2UrlManager
  • X2Validator
  • X2WidgetBehavior

Interfaces

  • AdminOwnedCredentials

Exceptions

  • CampaignMailingException
  • CodeExchangeException
  • GetCredentialsException
  • NoRefreshTokenException
  • NoUserIdException
  • StringUtilException

Functions

  • checkCurrency
  • checkDNS
  • checkServerVar
  • checkTimezone
  • decodeQuotes
  • echoIcons
  • encodeQuotes
  • exceptionForError
  • getField
  • getLanguageName
  • getModuleTitle
  • handleReqError
  • handleReqException
  • installer_t
  • installer_tr
  • isAllowedDir
  • mediaMigrationRrmdir
  • migrateMediaDir
  • printGraph
  • printR
  • renderFields
  • reqShutdown
  • RIP
  • translateOptions
  • tryGetRemote
  • Overview
  • Package
  • Class
  • Tree
  1: <?php
  2: /*****************************************************************************************
  3:  * X2Engine Open Source Edition is a customer relationship management program developed by
  4:  * X2Engine, Inc. Copyright (C) 2011-2016 X2Engine Inc.
  5:  * 
  6:  * This program is free software; you can redistribute it and/or modify it under
  7:  * the terms of the GNU Affero General Public License version 3 as published by the
  8:  * Free Software Foundation with the addition of the following permission added
  9:  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 10:  * IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
 11:  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 12:  * 
 13:  * This program is distributed in the hope that it will be useful, but WITHOUT
 14:  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 15:  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 16:  * details.
 17:  * 
 18:  * You should have received a copy of the GNU Affero General Public License along with
 19:  * this program; if not, see http://www.gnu.org/licenses or write to the Free
 20:  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 21:  * 02110-1301 USA.
 22:  * 
 23:  * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
 24:  * California 95067, USA. or at email address contact@x2engine.com.
 25:  * 
 26:  * The interactive user interfaces in modified source and object code versions
 27:  * of this program must display Appropriate Legal Notices, as required under
 28:  * Section 5 of the GNU Affero General Public License version 3.
 29:  * 
 30:  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 31:  * these Appropriate Legal Notices must retain the display of the "Powered by
 32:  * X2Engine" logo. If the display of the logo is not reasonably feasible for
 33:  * technical reasons, the Appropriate Legal Notices must display the words
 34:  * "Powered by X2Engine".
 35:  *****************************************************************************************/
 36: 
 37: /**
 38:  * Standalone class with miscellaneous utility functions
 39:  */
 40: class AuxLib {
 41: 
 42:     /**
 43:      * @param int $errCode php file upload error code 
 44:      */
 45:     public static function getFileUploadErrorMessage ($errCode) {
 46:         switch ($errCode) {
 47:             case UPLOAD_ERR_OK:
 48:                 break;
 49:             case UPLOAD_ERR_FORM_SIZE:
 50:             case UPLOAD_ERR_INI_SIZE:
 51:                 $errMsg = Yii::t('app', 'File exceeds the maximum upload size.');
 52:                 break;
 53:             case UPLOAD_ERR_PARTIAL:
 54:                 $errMsg = Yii::t('app', 'File upload was not completed.');
 55:                 break;
 56:             case UPLOAD_ERR_NO_FILE:
 57:                 $errMsg = Yii::t('app', 'Zero-length file uploaded.');
 58:                 break;
 59:             case UPLOAD_ERR_NO_TMP_DIR:
 60:                 break;
 61:             case UPLOAD_ERR_CANT_WRITE:
 62:                 break;
 63:             case UPLOAD_ERR_EXTENSION:
 64:                 break;
 65:             default: 
 66:                 $errMsg = Yii::t('app', 'Failed to upload file.');
 67:         }
 68:         return $errMsg;
 69:     }
 70: 
 71:     /**
 72:      * @return bool True if the file upload failed with errors, false otherwise
 73:      */
 74:     public static function checkFileUploadError ($name) {
 75:         if (!isset ($_FILES[$name])) return false;
 76:         if(empty($_FILES[$name]['tmp_name'])) 
 77:             return true;
 78:         return false;
 79:     }
 80: 
 81:     /**
 82:      * Registers a script which instantiates a dictionary of translations.
 83:      * @param string $scriptName The name of the script which will be registered
 84:      *   and which will be a property of the global JS object x2.
 85:      * @param array $messages An associateive array (<message label> => <untranslated message>)
 86:      * @param string $translationFile The first parameter to Yii::t
 87:      * @param string $namespace The name of the JS object which will contain the translations
 88:      *  dictiory
 89:      */
 90:     public static function registerTranslationsScript (
 91:         $namespace, $messages, $translationFile='app', $scriptName='passMsgsToClientScript') {
 92: 
 93:         $passVarsToClientScript = "
 94:             if (!x2.".$namespace.") x2.".$namespace." = {};
 95:             x2.".$namespace.".translations = {};
 96:         ";
 97:         foreach ($messages as $key=>$val) {
 98:             $passVarsToClientScript .= "x2.".$namespace.".translations['".
 99:                 $key. "'] = '" . addslashes (Yii::t($translationFile, $val)) . "';\n";
100:         }
101:         Yii::app()->clientScript->registerScript(
102:             $scriptName, $passVarsToClientScript,
103:             CClientScript::POS_HEAD);
104:     }
105: 
106:     /**
107:      * @param string $namespace The name of the JS object which will contain the translations
108:      *  dictionary. For nested namespaces, each namespace should be separated by a '.' character.
109:      * @param array $vars An associative array (<var name> => <var value>)
110:      * @param string $scriptName The name of the script which will be registered
111:      *   and which will be a property of the global JS object x2.
112:      */
113:     public static function registerPassVarsToClientScriptScript (
114:         $namespace, $vars, $scriptName='passVarsToClientScript') {
115: 
116:         $namespaces = explode ('.', $namespace);
117:         $rootNamespace = array_shift ($namespaces);
118: 
119:         // declare nested namespaces one at a time if they don't already exist, starting at the root
120:         $passVarsToClientScript = "
121:             ;(function () {
122:                 if (typeof ".$rootNamespace." === 'undefined') ".$rootNamespace." = {};
123:                 var namespaces = ".CJSON::encode ($namespaces).";
124:                 var prevNameSpace = ".$rootNamespace.";
125: 
126:                 for (var i in namespaces) {
127:                     if (typeof prevNameSpace[namespaces[i]] === 'undefined') {
128:                         prevNameSpace[namespaces[i]] = {};
129:                     }
130:                     prevNameSpace = prevNameSpace[namespaces[i]];
131:                 }
132:             }) ();
133:         ";
134:         foreach ($vars as $key=>$val) {
135:             $passVarsToClientScript .= $namespace.".".$key." = ".$val.";";
136:         }
137:         Yii::app()->clientScript->registerScript(
138:             $scriptName, $passVarsToClientScript,
139:             CClientScript::POS_HEAD);
140:     }
141: 
142:     /**
143:      * Used by actions to return JSON encoded array containing error status and error message.
144:      * Used for testing purposes only.
145:      */
146:     public static function printTestError ($message) {
147:         if (YII_DEBUG) echo CJSON::encode (array ('error' => array (Yii::t('app', $message))));
148:     }
149: 
150:     /**
151:      * Used by actions to return JSON encoded array containing error status and error message.
152:      */
153:     public static function printError ($message) {
154:         echo CJSON::encode (array (false, $message));
155:     }
156: 
157:     /**
158:      * Used by actions to return JSON encoded array containing success status and success message.
159:      */
160:     public static function printSuccess ($message) {
161:         echo CJSON::encode (array (true, $message));
162:     }
163: 
164:     /**
165:      * Calls printError or printSuccess depending on the value of $success.
166:      *
167:      * @param bool $success 
168:      * @param string $successMessage
169:      * @param string $errorMessage
170:      * @return array (<bool>, <string>)
171:      */
172:     public static function ajaxReturn ($success, $successMessage, $errorMessage) {
173:         if ($success) {
174:             self::printSuccess ($successMessage);
175:         } else { // !$success
176:             self::printError ($errorMessage);
177:         }
178:     }
179: 
180:     /**
181:      * Used to log debug messages
182:      */
183:     public static function debugLog ($message) {
184:         if (!YII_DEBUG) return;
185:         Yii::log ($message, 'error', 'application.debug');
186:     }
187: 
188:     public static function debugLogR ($arr) {
189:         if (!YII_DEBUG) return;
190:         $logMessage = print_r ($arr, true);
191:         Yii::log ($logMessage, 'error', 'application.debug');
192:     }
193: 
194:     /**
195:      * Render a hex dump to the debug log
196:      * Adapted from: https://stackoverflow.com/a/4225813
197:      */
198:     public static function debugLogHd ($data) {
199:         if (!YII_DEBUG) return;
200:         static $from = '';
201:         static $to = '';
202:         static $width = 16; # number of bytes per line
203:         static $pad = '.'; # padding for non-visible characters
204: 
205:         if ($from==='') {
206:             for ($i=0; $i<=0xFF; $i++) {
207:                 $from .= chr($i);
208:                 $to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
209:             }
210:         }
211: 
212:         $hex = str_split(bin2hex($data), $width*2);
213:         $chars = str_split(strtr($data, $from, $to), $width);
214: 
215:         $output = "\n"; // begin on next line
216:         $offset = 0;
217:         foreach ($hex as $i => $line) {
218:             $hexBytes = str_split($line, 16);
219:             $hexContent = implode(' ', str_split($hexBytes[0],2));
220:             if (isset($hexBytes[1]))
221:                 $hexContent .= '  '.implode(' ', str_split($hexBytes[1],2));
222:             $output .= sprintf('%06X  %-48s',$offset, $hexContent). ' |' . $chars[$i] . "|\n";
223:             $offset += $width;
224:         }
225:         self::debugLog ($output);
226:     }
227: 
228:     /**
229:      * Generic version of debugLogR 
230:      */
231:     public static function logR ($arr, $route) {
232:         $logMessage = print_r ($arr, true);
233:         Yii::log ($logMessage, 'error', 'application.'.$route);
234:     }
235: 
236:     public static function debugLogExport ($arr) {
237:         if (!YII_DEBUG) return;
238:         $logMessage = var_export ($arr, true);
239:         Yii::log ($logMessage, 'error', 'application.debug');
240:     }
241: 
242:     public static function isIE8 () {
243:         $userAgentStr = strtolower(Yii::app()->request->userAgent);
244:         return preg_match('/msie 8/i', $userAgentStr);
245:     }
246: 
247:     public static function isIE () {
248:         $userAgentStr = strtolower(Yii::app()->request->userAgent);
249:         return preg_match('/msie/i', $userAgentStr);
250:     }
251: 
252:     public static function isAndroid () {
253:         $userAgentStr = strtolower(Yii::app()->request->userAgent);
254:         return preg_match('/android/', $userAgentStr);
255:     }
256: 
257:     public static function isIPad () {
258:         $userAgentStr = strtolower(Yii::app()->request->userAgent);
259:         return preg_match('/ipad/', $userAgentStr);
260:     }
261: 
262:     public static function getLayoutType () {
263:         $pathInfo = strtolower(Yii::app()->request->getPathInfo ());
264:         if (AuxLib::isIE8 () || strpos ($pathInfo, 'admin') === 0 ||
265:             preg_match ('/flowDesigner(\/\d+)?$/', $pathInfo)) {
266: 
267:             return 'static';
268:         } else {
269:             return 'responsive';
270:         }
271:     }
272: 
273:     /**
274:      * @return mixed The IE version if available, otherwise infinity 
275:      */
276:     public static function getIEVer () {
277:         $userAgentStr = strtolower(Yii::app()->request->userAgent);
278:         preg_match('/msie ([0-9]+)/', $userAgentStr, $matches);
279:         if (sizeof ($matches) === 2) {
280:             $ver = (int) $matches[1];
281:         } else {
282:             $ver = INF;
283:         }
284:         return $ver;
285:     }
286: 
287:     public static function setCookie ($key, $val, $time) {
288:         if (YII_DEBUG) { // workaround which allows chrome to set cookies for localhost
289:             $serverName = Yii::app()->request->getServerName() === 'localhost' ? '' :
290:                 Yii::app()->request->getServerName();
291:         } else {
292:             $serverName = Yii::app()->request->getServerName();
293:         }
294:         setcookie($key,$val,time()+$time,dirname(Yii::app()->request->getScriptUrl()), $serverName);
295:     }
296: 
297:     public static function clearCookie ($key){
298:         if(YII_DEBUG){ // workaround which allows chrome to set cookies for localhost
299:             $serverName = Yii::app()->request->getServerName() === 'localhost' ? '' :
300:                     Yii::app()->request->getServerName();
301:         }else{
302:             $serverName = Yii::app()->request->getServerName();
303:         }
304:         unset($_COOKIE[$key]);
305:         setcookie(
306:             $key, '', time() - 3600, dirname(Yii::app()->request->getScriptUrl()), $serverName);
307:     }
308: 
309:     /**
310:      * Generates parameter binding placeholders for each element in array
311:      * @param array $arr parameter values to be bound in a SQL query
312:      * @param string $prefix prefix to use for paramater names
313:      * @return array parameter values indexed by parameter name
314:      */
315:     public static function bindArray ($arr, $prefix='X2') {
316:         $placeholders = array ();
317:         $arrLen = sizeof ($arr);
318:         for ($i = 0; $i < $arrLen; ++$i) {
319:             $placeholders[] = ':' . $prefix . $i;
320:         }
321:         if ($arrLen === 0) {
322:             return array ();
323:         } 
324:         return array_combine ($placeholders, $arr);
325:     }
326: 
327:     public static function arrToStrList ($arr) {
328:         return '('.implode (',', $arr).')';
329:     }
330: 
331:     /**
332:      * @deprecated 
333:      */
334:     public static function coerceToArray (&$arr) {
335:         $arr = ArrayUtil::coerceToArray ($arr);
336:     }
337: 
338:     /**
339:      * Prints stack trace 
340:      * @param int $limit If set, only the top $limit items on the call stack will get printed. 
341:      *  debug_backtrace does have an optional limit argument, but it wasn't introduced until php
342:      *  5.4.0.
343:      */
344:     public static function trace ($limit=null) {
345:         if ($limit !== null) {
346:             /**/AuxLib::debugLogR (
347:                 array_slice (debug_backtrace (DEBUG_BACKTRACE_IGNORE_ARGS), 0, $limit));
348:         } else {
349:             /**/AuxLib::debugLogR (debug_backtrace (DEBUG_BACKTRACE_IGNORE_ARGS));
350:         }
351:     }
352: 
353:     /**
354:      * Reformats and translates dropdown arrays to preserve sorting in {@link CJSON::encode()}
355:      * @param array an associative array of dropdown options ($value => $label)
356:      * @return array a 2-D array of values and labels
357:      */
358:     public static function dropdownForJson($options) {
359:         $dropdownData = array();
360:         foreach($options as $value => &$label)
361:             $dropdownData[] = array($value,$label);
362:         return $dropdownData;
363:     }
364: 
365:     public static function println ($message) {
366:         /**/print ($message."\n");
367:     }
368: 
369:     public static function issetIsArray ($param) {
370:         return (isset ($param) && is_array ($param));
371:     }
372: 
373:     public static function captureOutput ($fn) {
374:         ob_start();
375:         ob_implicit_flush(false);
376:         $fn ();
377:         return ob_get_clean();
378:     }
379: 
380:     // Determines if the user is using a Mac
381:     public static function isMac () {
382:         $user_agent = getenv ("HTTP_USER_AGENT");
383:         return (strpos ($user_agent, "Mac") !== false);
384:     }
385: 
386:     // Returns if the current request was made with ajax
387:     public static function isAjax () {
388:         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
389: 
390:     }
391: 
392:     public static function getRequestUrl () {
393:         $protocol = !empty ($_SERVER['HTTPS']) ? 'https' : 'http';
394:         $baseUrl = $protocol . '://' . $_SERVER['HTTP_HOST'];
395:         $uri = $_SERVER['REQUEST_URI'];
396:         return $baseUrl.$uri;
397:     }
398:     
399:     
400: }
401: 
X2CRM Documentation API documentation generated by ApiGen 2.8.0