Ejemplo n.º 1
0
/**
 * @ignore
 */
function vs($dummy, $vars)
{
    // This internal function is used by assertions to put debugging information about the variables that are defined
    // at the point of a failing assertion and the object's properties at that point into a string to subsequently log
    // it into a file, send it by mail to the administrator etc.
    if (assert_options(ASSERT_ACTIVE) !== 1) {
        // Assertions are disabled, so nothing to do.
        return;
    }
    return CDebug::definedVarsToString($vars);
}
Ejemplo n.º 2
0
 /**
  * Sorts the elements in an array by comparing return values from a specified method being called on each element.
  *
  * For example, if you had an array of UserClass objects and UserClass had a public method named `numPosts` that
  * would return an integer value, you could sort the users by the number of posts they've made by calling this
  * method with "numPosts" as the value of `$onMethodName` parameter.
  *
  * If you want to pass any custom arguments to the method that the array needs to be sorted on, just add them after
  * the comparator parameter when calling this method and the custom arguments will be passed to that method in the
  * same order.
  *
  * The method on which the array needs to be sorted can be static and, in this case, every element for which that
  * method is called is passed to that method as the first argument, in front of any custom arguments if they are
  * used.
  *
  * You can use your own comparator for the comparison of return values for the elements in the array, but the
  * default comparators, such as `CComparator::ORDER_ASC` and `CComparator::ORDER_DESC`, have got you covered when
  * sorting by scalar values, such as `string`, `int`, `float`, and `bool` in the ascending or descending order
  * respectively. And the default comparators are smart enough to know how to compare objects of those classes that
  * conform to the IEqualityAndOrder interface (static or not), including CArray and CMap. See the
  * [CComparator](CComparator.html) class for more on this.
  *
  * @param  array $array The array to be sorted.
  * @param  string $onMethodName The name of the method on which the elements are to be sorted.
  * @param  callable $comparator **OPTIONAL. Default is** `CComparator::ORDER_ASC`. The function or method to be
  * used for the comparison of any two return values. If this parameter is provided, the comparator should take two
  * parameters, which are the return values for the two elements being compared, and return `-1` if the first
  * element needs to go before the second element in the sorted array, `1` if the other way around, and `0` if the
  * two elements are considered equal based on the return values.
  *
  * @return void
  *
  * @link   CComparator.html CComparator
  */
 public static function sortOn($array, $onMethodName, $comparator = CComparator::ORDER_ASC)
 {
     assert('is_carray($array) && is_cstring($onMethodName) && is_callable($comparator)', vs(isset($this), get_defined_vars()));
     $array = splarray($array);
     static $s_methodArgsStartPos = 3;
     $methodArgs = func_num_args() == $s_methodArgsStartPos ? [] : array_slice(func_get_args(), $s_methodArgsStartPos);
     $useComparator = function ($element0, $element1) use($onMethodName, $comparator, $methodArgs) {
         $className;
         $typeIsNonScalar = phred_classify_duo($element0, $element1, $className);
         if (CDebug::isDebugModeOn()) {
             // Except for a few special cases, any two elements being compared must be objects of the same
             // class.
             assert('$typeIsNonScalar', vs(isset($this), get_defined_vars()));
             $className0;
             $className1;
             phred_classify($element0, $className0);
             phred_classify($element1, $className1);
             assert('CString::equals($className0, $className1)', vs(isset($this), get_defined_vars()));
         }
         $reflClass = new ReflectionClass($className);
         assert('$reflClass->hasMethod($onMethodName)', vs(isset($this), get_defined_vars()));
         $reflMethod = $reflClass->getMethod($onMethodName);
         assert('$reflMethod->isPublic()', vs(isset($this), get_defined_vars()));
         $methodInvokeRes0;
         $methodInvokeRes1;
         if (!$reflMethod->isStatic()) {
             if (empty($methodArgs)) {
                 $methodInvokeRes0 = $reflMethod->invoke($element0);
                 $methodInvokeRes1 = $reflMethod->invoke($element1);
             } else {
                 $methodInvokeRes0 = $reflMethod->invokeArgs($element0, $methodArgs);
                 $methodInvokeRes1 = $reflMethod->invokeArgs($element1, $methodArgs);
             }
         } else {
             if (empty($methodArgs)) {
                 $methodInvokeRes0 = $reflMethod->invoke(null, $element0);
                 $methodInvokeRes1 = $reflMethod->invoke(null, $element1);
             } else {
                 $methodInvokeRes0 = $reflMethod->invokeArgs(null, $element0, $methodArgs);
                 $methodInvokeRes1 = $reflMethod->invokeArgs(null, $element1, $methodArgs);
             }
         }
         return call_user_func($comparator, $methodInvokeRes0, $methodInvokeRes1);
     };
     self::sort($array, $useComparator);
 }
Ejemplo n.º 3
0
 /**
  * @ignore
  */
 public static function initializeFramework()
 {
     $currEnv;
     if (!$GLOBALS["PHRED_TESTS"]) {
         // Try to get the name of the environment in which the application is currently running without the risk of
         // encountering an error or triggering an assertion, which could otherwise reveal sensitive debugging
         // information if "display_errors" happens to be enabled in php.ini.
         $appConfigFp = $GLOBALS["PHRED_PATH_TO_APP"] . "/Configuration" . "/Application.json";
         if (file_exists($appConfigFp)) {
             $appConfig = file_get_contents($appConfigFp);
             if (is_string($appConfig)) {
                 $matches;
                 $res = preg_match("/^\\h*\"environment\"\\s*:\\s*\"(\\w+)\"/m", $appConfig, $matches);
                 if ($res === 1) {
                     $currEnv = $matches[1];
                 }
             }
         }
     } else {
         $currEnv = "tst";
     }
     if (isset($currEnv)) {
         // Based on the current environment, set some debugging options to temporary values for the time while the
         // configuration is not yet read.
         if (strcasecmp($currEnv, "dev") == 0) {
             // Development.
             ini_set("display_errors", "On");
             CDebug::setAssertionsLevel1(true);
             CDebug::setAssertionsLevel2(false);
         } else {
             if (strcasecmp($currEnv, "pro") == 0) {
                 // Production.
                 ini_set("display_errors", "Off");
                 CDebug::setAssertionsLevel1(false);
                 CDebug::setAssertionsLevel2(false);
             } else {
                 if (strcasecmp($currEnv, "tst") == 0) {
                     // Testing.
                     ini_set("display_errors", "On");
                     CDebug::setAssertionsLevel1(true);
                     CDebug::setAssertionsLevel2(true);
                 } else {
                     // Unknown environment.
                     error_reporting(E_ALL);
                     ini_set("display_errors", "On");
                 }
             }
         }
     } else {
         error_reporting(E_ALL);
         ini_set("display_errors", "On");
         trigger_error("Could not read the name of the current environment.", E_USER_ERROR);
     }
     // Read all the configuration options.
     CConfiguration::initialize();
     // Set whether error messages should be shown is the output.
     if (CConfiguration::option("debug.displayErrors")) {
         ini_set("display_errors", "On");
     } else {
         ini_set("display_errors", "Off");
     }
     // Set the error reporting level.
     $errorReportingLevel = constant(CConfiguration::option("debug.errorReportingLevel"));
     error_reporting($errorReportingLevel);
     // Process the configuration options that are related to debugging.
     $debug = CConfiguration::option("debug");
     // Assertions and the conditions on which they get active.
     $assertionsAreActive = false;
     $assertionsAreEnabled = $debug["enableAssertions"];
     if ($assertionsAreEnabled) {
         $assertionsAreActiveBasedOn = $debug["assertionsAreActiveBasedOn"];
         if (CString::equalsCi($assertionsAreActiveBasedOn, "always")) {
             // Always.
             $assertionsAreActive = true;
         } else {
             // Reference time zone.
             $refTimeZone;
             $timeZoneName = $debug["referenceTimeZone"];
             if (!CString::isEmpty($timeZoneName)) {
                 $refTimeZone = new CTimeZone($timeZoneName);
             } else {
                 $refTimeZone = CTimeZone::makeUtc();
             }
             if (CString::equalsCi($assertionsAreActiveBasedOn, "hour")) {
                 // Current time.
                 $currTime = CTime::now();
                 // Hour.
                 $hourRanges = $debug["assertionsAreActiveWithinHourRange"];
                 $currHour = $currTime->hourInTimeZone($refTimeZone);
                 if (!is_carray($hourRanges[0])) {
                     $hourRanges = CArray::fromElements($hourRanges);
                 }
                 $len = CArray::length($hourRanges);
                 for ($i = 0; $i < $len; $i++) {
                     $range = $hourRanges[$i];
                     assert('is_int($range[0]) && is_int($range[1])', vs(isset($this), get_defined_vars()));
                     if ($range[0] <= $currHour && $currHour <= $range[1]) {
                         $assertionsAreActive = true;
                         break;
                     }
                 }
             } else {
                 if (CString::equalsCi($assertionsAreActiveBasedOn, "dayOfWeek")) {
                     // Current time.
                     $currTime = CTime::now();
                     // Day of week.
                     $daysOfWeek = $debug["assertionsAreActiveOnDaysOfWeek"];
                     if (!is_carray($daysOfWeek)) {
                         $daysOfWeek = CArray::fromElements($daysOfWeek);
                     }
                     $currDayOfWeek = $currTime->dayOfWeekInTimeZone($refTimeZone);
                     $currDayOfWeekShort;
                     switch ($currDayOfWeek) {
                         case CTime::SUNDAY:
                             $currDayOfWeekShort = "sun";
                             break;
                         case CTime::MONDAY:
                             $currDayOfWeekShort = "mon";
                             break;
                         case CTime::TUESDAY:
                             $currDayOfWeekShort = "tue";
                             break;
                         case CTime::WEDNESDAY:
                             $currDayOfWeekShort = "wed";
                             break;
                         case CTime::THURSDAY:
                             $currDayOfWeekShort = "thu";
                             break;
                         case CTime::FRIDAY:
                             $currDayOfWeekShort = "fri";
                             break;
                         case CTime::SATURDAY:
                             $currDayOfWeekShort = "sat";
                             break;
                     }
                     $len = CArray::length($daysOfWeek);
                     for ($i = 0; $i < $len; $i++) {
                         $dow = $daysOfWeek[$i];
                         assert('!CString::isEmpty($dow)', vs(isset($this), get_defined_vars()));
                         if (CString::equalsCi($currDayOfWeekShort, $dow)) {
                             $assertionsAreActive = true;
                             break;
                         }
                     }
                 } else {
                     if (CString::equalsCi($assertionsAreActiveBasedOn, "dayOfYear")) {
                         // Day of year.
                         $multiplier = $debug["assertionsAreActiveOnEveryDayOfYearMultipleOf"];
                         assert('is_int($multiplier)', vs(isset($this), get_defined_vars()));
                         $currDayOfYear = CTime::currentDayOfYearInTimeZone($refTimeZone);
                         if ($currDayOfYear % $multiplier == 0) {
                             $assertionsAreActive = true;
                         }
                     } else {
                         assert('false', vs(isset($this), get_defined_vars()));
                     }
                 }
             }
         }
     }
     if ($assertionsAreActive) {
         // Enable level 1 assertions.
         CDebug::setAssertionsLevel1(true);
         $enableAssertionsLevel2 = $debug["enableAssertionsLevel2"];
         if ($enableAssertionsLevel2) {
             // Enable level 2 assertions.
             CDebug::setAssertionsLevel2(true);
         }
     } else {
         CDebug::setAssertionsLevel1(false);
         CDebug::setAssertionsLevel2(false);
     }
     // Logging.
     $logging = $debug["logging"];
     $loggingIsEnabled = $logging["enable"];
     if ($loggingIsEnabled) {
         $logFp = $logging["logFilePath"];
         assert('!CString::isEmpty($logFp)', vs(isset($this), get_defined_vars()));
         $logFp = CFilePath::frameworkPath($logFp);
         CDebug::setLogging($logFp);
     }
     // Mailing.
     $mailing = $debug["mailing"];
     $mailingIsEnabled = $mailing["enable"];
     if ($mailingIsEnabled) {
         $adminMail = CConfiguration::option("admin.mail");
         $to = $adminMail["to"];
         $from = $adminMail["from"];
         $transport = $adminMail["transport"];
         assert('!CString::isEmpty($to) && !CString::isEmpty($from) && !CString::isEmpty($transport)', vs(isset($this), get_defined_vars()));
         $minTimeBetweenSendMailHours = $mailing["minTimeBetweenSendMailHours"];
         assert('is_int($minTimeBetweenSendMailHours)', vs(isset($this), get_defined_vars()));
         $mail;
         if (CString::equalsCi($transport, "smtp")) {
             $smtpOutgoingServer = $adminMail["smtpOutgoingServer"];
             $smtpUsername = $adminMail["smtpUsername"];
             $smtpPassword = $adminMail["smtpPassword"];
             assert('!CString::isEmpty($smtpOutgoingServer) && !CString::isEmpty($smtpUsername) && ' . '!CString::isEmpty($smtpPassword)', vs(isset($this), get_defined_vars()));
             $mail = CMail::makeSmtp($smtpOutgoingServer, $smtpUsername, $smtpPassword, $from, $to);
         } else {
             if (CString::equalsCi($transport, "system")) {
                 $mail = CMail::makeSystem($from, $to);
             } else {
                 assert('false', vs(isset($this), get_defined_vars()));
             }
         }
         CDebug::setMailing($mail, $minTimeBetweenSendMailHours);
     }
 }
Ejemplo n.º 4
0
 /**
  * Determines the order in which two values should appear in a place where it matters, assuming the ascending
  * order.
  *
  * If the values are objects of your custom class, the class should conform to the
  * [IEqualityAndOrder](IEqualityAndOrder.html) interface.
  *
  * @param  mixed $value0 The first value for comparison.
  * @param  mixed $value1 The second value for comparison.
  *
  * @return int A negative value (typically `-1`) if the first value should go before the second value, a positive
  * value (typically `1`) if the other way around, and `0` if the two values are equal.
  *
  * @link   IEqualityAndOrder.html IEqualityAndOrder
  */
 public static function orderAsc($value0, $value1)
 {
     if (CDebug::isDebugModeOn()) {
         if (!(is_cstring($value0) && is_cstring($value1) || is_carray($value0) && is_carray($value1) || is_cmap($value0) && is_cmap($value1))) {
             // With the above exceptions, the two values should be both either scalars or objects of the same
             // class.
             assert('is_object($value0) == is_object($value1)', vs(isset($this), get_defined_vars()));
             assert('!is_object($value0) || CString::equals(get_class($value0), get_class($value1))', vs(isset($this), get_defined_vars()));
         }
     }
     $className;
     if (!phred_classify_duo($value0, $value1, $className)) {
         // Compare the values as scalars.
         assert('(is_scalar($value0) || is_null($value0)) && (is_scalar($value1) || is_null($value1))', vs(isset($this), get_defined_vars()));
         return $value0 === $value1 ? 0 : ($value0 < $value1 ? -1 : 1);
     } else {
         // Compare the values as objects that may conform to one of the comparison interfaces.
         $reflClass = new ReflectionClass($className);
         if ($reflClass->implementsInterface("IEqualityAndOrderStatic")) {
             $res = call_user_func([$className, "compare"], $value0, $value1);
             assert('is_int($res)', vs(isset($this), get_defined_vars()));
             return $res;
         }
         if ($reflClass->implementsInterface("IEqualityAndOrder")) {
             $res = call_user_func([$value0, "compare"], $value1);
             assert('is_int($res)', vs(isset($this), get_defined_vars()));
             return $res;
         }
         // The class of the objects being compared does not implement any applicable comparison interfaces.
         assert('false', vs(isset($this), get_defined_vars()));
     }
 }
Ejemplo n.º 5
0
 /**
  * Sets the options for an FTP request.
  *
  * @param  bool $createMissingDirectoriesForUpload Tells whether to try creating missing directories when
  * uploading a file.
  * @param  bool $appendUpload **OPTIONAL. Default is** `false`. Tells whether the data from the file being
  * uploaded should be appended to the data of the existing file, if any.
  * @param  array $quoteCommands **OPTIONAL. Default is** *none*. The (S)FTP commands to be run before the transfer.
  * @param  array $postQuoteCommands **OPTIONAL. Default is** *none*. The (S)FTP commands to be run after the
  * transfer.
  * @param  bool $useEpsv **OPTIONAL. Default is** `true`. Tells whether to use EPSV.
  * @param  string $activeModeBackAddress **OPTIONAL. Default is** *cURL's default*. The client-side address to
  * which the destination server should try connecting back.
  * @param  bool $useEprt **OPTIONAL. Default is** `true`. Tells whether to use EPRT.
  *
  * @return void
  */
 public function setFtpOptions($createMissingDirectoriesForUpload, $appendUpload = false, $quoteCommands = null, $postQuoteCommands = null, $useEpsv = true, $activeModeBackAddress = null, $useEprt = true)
 {
     assert('is_bool($createMissingDirectoriesForUpload) && is_bool($appendUpload) && ' . '(!isset($quoteCommands) || is_carray($quoteCommands)) && (!isset($postQuoteCommands) || ' . 'is_carray($postQuoteCommands)) && is_bool($useEpsv) && (!isset($activeModeBackAddress) || ' . 'is_cstring($activeModeBackAddress)) && is_bool($useEprt)', vs(isset($this), get_defined_vars()));
     assert('$this->isFtp()', vs(isset($this), get_defined_vars()));
     if (CDebug::isDebugModeOn()) {
         if (isset($quoteCommands)) {
             $len = CArray::length($quoteCommands);
             for ($i = 0; $i < $len; $i++) {
                 assert('is_cstring($quoteCommands[$i])', vs(isset($this), get_defined_vars()));
             }
         }
         if (isset($postQuoteCommands)) {
             $len = CArray::length($postQuoteCommands);
             for ($i = 0; $i < $len; $i++) {
                 assert('is_cstring($postQuoteCommands[$i])', vs(isset($this), get_defined_vars()));
             }
         }
     }
     $this->m_ftpCreateMissingDirectoriesForUpload = $createMissingDirectoriesForUpload;
     $this->m_ftpAppendUpload = $appendUpload;
     $this->m_ftpQuoteCommands = $quoteCommands;
     $this->m_ftpPostQuoteCommands = $postQuoteCommands;
     $this->m_ftpUseEpsv = $useEpsv;
     $this->m_ftpActiveModeBackAddress = $activeModeBackAddress;
     $this->m_ftpUseEprt = $useEprt;
 }
Ejemplo n.º 6
0
 public static function setMailing(CMail $mail, $minTimeBetweenSendMailHours = self::DEFAULT_MIN_TIME_BETWEEN_SEND_MAIL_HOURS)
 {
     // Enables mailing about encountered errors with the provided CMail object.
     assert('is_int($minTimeBetweenSendMailHours)', vs(isset($this), get_defined_vars()));
     assert('$minTimeBetweenSendMailHours >= 0', vs(isset($this), get_defined_vars()));
     self::$ms_mailing = true;
     self::$ms_mail = $mail;
     self::$ms_minTimeBetweenSendMailHours = $minTimeBetweenSendMailHours;
     self::registerHandlers();
 }
Ejemplo n.º 7
0
 public function query($sSQL, $sNombreTabla = "")
 {
     $sDbType = $this->_sType;
     $arTabla = array();
     switch ($sDbType) {
         case "mysql":
             $arTabla = $this->query_mysql($sSQL, $sNombreTabla);
             break;
         case "sqlserver":
             $arTabla = $this->query_mssql($sSQL, $sNombreTabla);
         default:
             break;
     }
     CDebug::set_sql($sSQL, count($sSQL));
     return $arTabla;
 }
Ejemplo n.º 8
0
 /**
  * Adds a field to a URL query.
  *
  * Query strings allow for field values to be arrays and maps that can contain not only strings but also other
  * arrays and maps, and so on. If the field's value is a string, the characters in it should be represented
  * literally and no characters should be percent-encoded.
  *
  * @param  string $fieldName The name of the field. The characters in the string should be represented literally
  * and no characters should be percent-encoded.
  * @param  mixed $value The value of the field. This can be a string (the most common case), a `bool`, an `int`, a
  * `float`, an array, or a map.
  *
  * @return void
  */
 public function addField($fieldName, $value)
 {
     assert('is_cstring($fieldName) && (is_cstring($value) || ' . 'is_bool($value) || is_int($value) || is_float($value) || is_collection($value))', vs(isset($this), get_defined_vars()));
     if (CDebug::isDebugModeOn()) {
         self::recurseFieldValidation($value, 0);
     }
     $this->m_query[$fieldName] = $value;
 }
Ejemplo n.º 9
0
 /**
  * Encodes the map or array provided earlier to the encoder into a JSON string and returns it.
  *
  * @return CUStringObject The resulting JSON string.
  */
 public function encode()
 {
     assert('is_cmap($this->m_source) || is_carray($this->m_source)', vs(isset($this), get_defined_vars()));
     $source = $this->m_source;
     if (CDebug::assertionsLevel2()) {
         // Check character encodings in string values.
         self::recurseStringValidation($source, 0);
     }
     $source = self::recurseValueBeforeEncoding($source, 0);
     $options = 0;
     if (!$this->m_escapeNonAsciiChars) {
         $options |= JSON_UNESCAPED_UNICODE;
     }
     if (!$this->m_escapeForwardSlashes) {
         $options |= JSON_UNESCAPED_SLASHES;
     }
     if ($this->m_escapeAngleBrackets) {
         $options |= JSON_HEX_TAG;
     }
     if ($this->m_escapeAmpersands) {
         $options |= JSON_HEX_AMP;
     }
     if ($this->m_escapeSingleQuotes) {
         $options |= JSON_HEX_APOS;
     }
     if ($this->m_escapeDoubleQuotes) {
         $options |= JSON_HEX_QUOT;
     }
     if ($this->m_prettyPrint) {
         $options |= JSON_PRETTY_PRINT;
     }
     $encodedValue = json_encode($source, $options, self::$ms_maxRecursionDepth);
     assert('is_cstring($encodedValue) && !CString::isEmpty($encodedValue)', vs(isset($this), get_defined_vars()));
     return $encodedValue;
 }