/** * Creates a temporary image and executes the given actions. By creating a * temporary copy of the image before manipulating it, this process is atomic. */ public function process($image, $actions, $dir, $file, $render = FALSE) { // We only need the filename $image = $image['file']; // Unique temporary filename $this->tmp_image = $dir.'k2img--'.sha1(time().$dir.$file).substr($file, strrpos($file, '.')); // Copy the image to the temporary file copy($image, $this->tmp_image); // Quality change is done last $quality = (int) CArray::remove('quality', $actions); // Use 95 for the default quality empty($quality) and $quality = 95; // All calls to these will need to be escaped, so do it now $this->cmd_image = escapeshellarg($this->tmp_image); $this->new_image = ($render)? $this->cmd_image : escapeshellarg($dir.$file); if ($status = $this->execute($actions)) { // Use convert to change the image into its final version. This is // done to allow the file type to change correctly, and to handle // the quality conversion in the most effective way possible. if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -quality '.$quality.'% '.$this->cmd_image.' '.$this->new_image)) { $this->errors[] = $error; } else { // Output the image directly to the browser if ($render !== FALSE) { $contents = file_get_contents($this->tmp_image); switch (substr($file, strrpos($file, '.') + 1)) { case 'jpg': case 'jpeg': header('Content-Type: image/jpeg'); break; case 'gif': header('Content-Type: image/gif'); break; case 'png': header('Content-Type: image/png'); break; } echo $contents; } } } // Remove the temporary image unlink($this->tmp_image); $this->tmp_image = ''; return $status; }
/** * @static * @param $img resource * @param $imginfo array */ public static function getLogoPosition($img, $imginfo) { list($w, $h) = $imginfo; $ds = array(); foreach (self::$positions as $pos => $colorcheck) { foreach ($colorcheck as $coltxt => $coord) { if ($coord['x'] < 0) { $coord['x'] = $w + $coord['x']; } if ($coord['y'] < 0) { $coord['y'] = $h + $coord['y']; } $color = imagecolorat($img, $coord['x'], $coord['y']); // echo "({$coord['x']}, {$coord['y']})"; // echo "| $pos " . dechex($color); $ds[$pos][$coltxt] = self::colorMeasure($color, $coord['color']); } } // $ds2[$color][$position] $ds2 = CArray::rotate($ds); $mincolord = array(); $counts = array(); foreach ($ds2 as $col => $poss) { $min = 1024; $key = 0; foreach ($poss as $pos => $d) { if ($min > $d) { $key = $pos; $min = $d; } } $mincolord[$col]['pos'] = $key; $mincolord[$col]['d'] = $min; $counts[$key] = 0; } // minimal color distance foreach ($mincolord as $col => $data) { if ($data['d'] < 100) { $counts[$data['pos']]++; } } // return $counts; foreach ($counts as $k => $v) { if ($v == 2) { return $k; } // ==count($mincolord) } if (array_sum($counts) == 0) { return false; } return $counts; }
public function __construct($rawData = []) { $nalog_info = \CArray::get($rawData, "nalog_info", []); $register_info = \CArray::get($rawData, "register_info", []); $address = \CArray::get($rawData, "address", []); $personal = \CArray::get($rawData, "personal", []); $names = \CArray::get($rawData, "names", []); $kapital = \CArray::get($rawData, "kapital", []); $trusted_personal = \CArray::get($rawData, "trusted_personal", []); $okved = \CArray::get($rawData, "okved", []); $termination = \CArray::get($rawData, "termination", []); $status = \CArray::get($rawData, "status", []); $this->rawData = $rawData; $this->inn = \CArray::get($nalog_info, 'inn'); $this->ogrn = \CArray::get($register_info, 'ogrn'); if ($address) { if (!($this->city = \CArray::get($address, 'town'))) { $this->city = \CArray::get($address, 'subdivision'); } $this->city = \StringHelper::ucfirst(trim(str_replace('ГОРОД', "", $this->city)), true); unset($address["grn_and_date"]); $this->address = join(', ', $address); } if ($personal) { $secondname = \StringHelper::ucfirst(\CArray::get($personal, 'secondname'), true); $name = \StringHelper::ucfirst(\CArray::get($personal, 'name'), true); $patronymic = \StringHelper::ucfirst(\CArray::get($personal, 'patronymic'), true); $nameL = mb_substr($name, 0, 1, "UTF-8"); $patronymicL = mb_substr($patronymic, 0, 1, "UTF-8"); $this->full_name = join(' ', array_filter([$secondname, $name, $patronymic])); $this->short_name = join(' ', array_filter([$secondname, $nameL, $patronymicL])); $this->director = $this->full_name; } elseif ($names) { $this->full_name = \CArray::get($names, 'full_name'); $this->short_name = \CArray::get($names, 'short_name'); } $this->found = \CArray::get($kapital, 'size_rub'); if ($trusted_personal) { $secondname = \StringHelper::ucfirst(\CArray::get($trusted_personal, 'secondname'), true); $name = \StringHelper::ucfirst(\CArray::get($trusted_personal, 'name'), true); $patronymic = \StringHelper::ucfirst(\CArray::get($trusted_personal, 'patronymic'), true); $this->director = join(' ', [$secondname, $name, $patronymic]); } $this->isOrganization = $trusted_personal || $names; $this->register_date = strtotime(\CArray::get($register_info, 'register_date')); $this->activity = \StringHelper::lower(\CArray::get($okved, 'code_activity')); if ($termination) { $this->status = self::STATUS_TERMINATED; } elseif ($status) { $this->status = \StringHelper::ucfirst(\CArray::get($status, 'status'), true); } }
public function testMake() { $cookie = new CCookie("name", "value"); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("value")); $cookie = new CCookie("name", true); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("1")); $cookie = new CCookie("name", 1234); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("1234")); $cookie = new CCookie("name", 12.34); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("12.34")); $cookie = new CCookie("name", CArray::fe("a", "b", "c")); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("[\"a\",\"b\",\"c\"]")); $cookie = new CCookie("name", ["one" => "a", "two" => "b", "three" => "c"]); $this->assertTrue($cookie->name()->equals("name") && $cookie->value()->equals("{\"one\":\"a\",\"two\":\"b\",\"three\":\"c\"}")); }
protected function parseTempTechsTable() { $criteria = new CDbCriteria(); $criteria->limit = 1000; $criteria->offset = 7000; #$criteria->condition = 'id=429'; #$criteria->order = 'id desc'; $models = Tmp::model()->findAll($criteria); foreach ($models as $k => $model) { preg_match_all('|<TR BGCOLOR=#ECECEC><TD><P class=table1>(.*)</TD>(?:.*)<TD Bgcolor=#F5F5F5><P class=table>(.*)</TD>|isU', $model->techs_table, $out, PREG_PATTERN_ORDER); $tmp = array(); foreach ($out[2] as $i => $val) { if (!isset($tmp[$out[1][$i]])) { $tmp[$out[1][$i]] = trim(strip_tags($out[2][$i], '<br>')); } else { $tmp['_' . $out[1][$i]] = trim(strip_tags($out[2][$i], '<br>')); } } #d($tmp, true); $char = new Characteristic(); $models[$k]->mod = $tmp['Модель']; /********/ @(list($models[$k]->modificationManufactureStart, $models[$k]->modificationManufactureEnd) = explode('-', $tmp['Год выпуска'])); $models[$k]->modificationManufactureStart = intval($models[$k]->modificationManufactureStart) ? intval($models[$k]->modificationManufactureStart) : null; $models[$k]->modificationManufactureEnd = intval($models[$k]->modificationManufactureEnd) ? intval($models[$k]->modificationManufactureEnd) : null; /********/ $char->body = L::ritem('bodyType', trim($tmp['Кузов'])); if (($tmp['Кузов'] == 'Купе-кабриолет' || $tmp['Кузов'] == 'Купе-Родстер' || $tmp['Кузов'] == 'Купе-Кабриолет') && !L::ritem('bodyType', trim($tmp['Кузов']))) { $char->body = 20; } if (($tmp['Кузов'] == 'Хэтчбэк' || $tmp['Кузов'] == 'Хэчтбек' || $tmp['Кузов'] == 'Седан<BR>Хэтчбек') && !L::ritem('bodyType', trim($tmp['Кузов']))) { $char->body = 3; } if ($tmp['Кузов'] == 'Landaulet' && !L::ritem('bodyType', trim($tmp['Кузов']))) { $char->body = 21; } if ($tmp['Кузов'] == 'Компактвен' && !L::ritem('bodyType', trim($tmp['Кузов']))) { $char->body = 12; } if ($tmp['Кузов'] == 'Джип' && !L::ritem('bodyType', trim($tmp['Кузов']))) { $char->body = 6; } @(list($char->doors, $char->seats) = explode('/', $tmp['Количество дверей/мест'])); @($char->weight = intval($tmp['Снаряженная масса, кг']) ? intval($tmp['Снаряженная масса, кг']) : null); @($char->weight_loaded = intval($tmp['Полная масса, кг']) ? intval($tmp['Полная масса, кг']) : null); @($char->trunk_capacity = $tmp['Объем багажника min/max, л']); @($char->length = intval($tmp['Длина']) ? intval($tmp['Длина']) : null); @($char->width = intval($tmp['Ширина']) ? intval($tmp['Ширина']) : null); @($char->height = intval($tmp['Высота']) ? intval($tmp['Высота']) : null); @($char->wheelbase = intval($tmp['Колесная база']) ? intval($tmp['Колесная база']) : null); #$char-> ??? = $tmp['Колея передняя/задняя']; $char->clearance = @$tmp['Дорожный просвет']; $char->turn_radius = @intval(str_replace(',', '.', $tmp['Минимальный радиус поворота, м'])); $char->displacement = @$tmp['Расположение']; if (isset($tmp['Число и расположение цилиндров']) && strstr($tmp['Число и расположение цилиндров'], 'V')) { $char->engine_type = 'V-образный, ' . mb_strtolower($tmp['Тип'], 'UTF-8'); } elseif (isset($tmp['Число и расположение цилиндров']) && strstr($tmp['Число и расположение цилиндров'], 'оппозитно')) { $char->engine_type = 'Оппозитный, ' . mb_strtolower($tmp['Тип'], 'UTF-8'); } elseif (isset($tmp['Число и расположение цилиндров']) && strstr($tmp['Число и расположение цилиндров'], 'в ряд')) { $char->engine_type = 'Рядный, ' . mb_strtolower($tmp['Тип'], 'UTF-8'); } $char->cylinders = intval(preg_replace('|[^0-9]|i', '', $tmp['Число и расположение цилиндров'])); $char->volume = $tmp['Рабочий объем, куб.см']; $char->valves = intval($tmp['Число клапанов']) ? intval($tmp['Число клапанов']) : null; if (isset($tmp['Мощность, л.с./ об/мин']) && strstr($tmp['Мощность, л.с./ об/мин'], '/')) { $t = explode('/', $tmp['Мощность, л.с./ об/мин']); $char->max_power = round(str_replace(',', '.', $t[0])); $char->max_power_rpm = $t[1]; } if (isset($tmp['Максимальный крутящий момент, Нхм / об/мин']) && strstr($tmp['Максимальный крутящий момент, Нхм / об/мин'], '/')) { $t = explode('/', $tmp['Максимальный крутящий момент, Нхм / об/мин']); $char->max_torque = $t[0]; $char->max_torque_rpm = $t[1]; } if (isset($tmp['_Тип']) && ($t = preg_split('/(\\(|<br>)/iU', $tmp['_Тип']))) { if (count($t) > 0) { foreach ($t as $t0) { if (empty($t0)) { continue; } $t0 = trim(preg_replace('|[\\(\\)]|is', '', $t0)); if (strstr($t0, 'Механи')) { $char->transmission_mt = $t0; $char->gears_mt = intval(preg_replace('|[^\\d]|is', '', $t0)); } else { $char->transmission_at = $t0; $char->gears_at = intval(preg_replace('|[^\\d]|is', '', $t0)); } } } } if (isset($tmp['Максимальная скорость, км/ч']) && ($t = preg_split('/(\\(|<br>|\\/)/iU', $tmp['Максимальная скорость, км/ч']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(preg_replace('|[\\(\\)]|is', '', $t[0])); $char->top_speed_mt = intval($t[0]) ? intval($t[0]) : null; } if (isset($t[1])) { $t[1] = trim(preg_replace('|[\\(\\)]|is', '', $t[1])); $char->top_speed_at = intval($t[1]) ? intval($t[1]) : null; } elseif (isset($char->transmission_at)) { $char->top_speed_at = $char->top_speed_mt; } } if (isset($tmp['Время разгона с места до 100 км/ч, с']) && ($t = preg_split('/(\\(|<br>|\\/)/iU', $tmp['Время разгона с места до 100 км/ч, с']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(preg_replace('|[\\(\\)]|is', '', $t[0])); $char->acceleration_mt = (double) $t[0] ? (double) $t[0] : null; } if (isset($t[1])) { $t[1] = trim(preg_replace('|[\\(\\)]|is', '', $t[1])); $char->acceleration_at = (double) $t[1] ? (double) $t[1] : null; } elseif (isset($char->transmission_at)) { $char->acceleration_at = $char->acceleration_mt; } } if (isset($tmp['Городской цикл']) && ($t = preg_split('/(\\(|<br>|\\/)/iU', $tmp['Городской цикл']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(preg_replace('|[\\(\\)]|is', '', $t[0])); $t[0] = str_replace(',', '.', $t[0]); $char->fuel_consumption_urban_mt = (double) $t[0] > 0 ? (double) $t[0] : null; } if (isset($t[1])) { $t[1] = trim(preg_replace('|[\\(\\)]|is', '', $t[1])); $t[1] = str_replace(',', '.', $t[1]); $char->fuel_consumption_urban_at = (double) $t[1] > 0 ? (double) $t[1] : null; } elseif (isset($char->transmission_at)) { $char->fuel_consumption_urban_at = $char->fuel_consumption_urban_mt; } } if (isset($tmp['Загородный цикл']) && ($t = preg_split('/(\\(|<br>|\\/)/iU', $tmp['Загородный цикл']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(preg_replace('|[\\(\\)]|is', '', $t[0])); $t[0] = str_replace(',', '.', $t[0]); $char->fuel_consumption_country_mt = (double) $t[0] > 0 ? (double) $t[0] : null; } if (isset($t[1])) { $t[1] = trim(preg_replace('|[\\(\\)]|is', '', $t[1])); $t[1] = str_replace(',', '.', $t[1]); $char->fuel_consumption_country_at = (double) $t[1] > 0 ? (double) $t[1] : null; } elseif (isset($char->transmission_at)) { $char->fuel_consumption_country_at = $char->fuel_consumption_country_mt; } } if (isset($tmp['Смешанный цикл']) && ($t = preg_split('/(\\(|<br>|\\/)/iU', $tmp['Смешанный цикл']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(preg_replace('|[\\(\\)]|is', '', $t[0])); $t[0] = str_replace(',', '.', $t[0]); $char->fuel_consumption_combined_mt = (double) $t[0] > 0 ? (double) $t[0] : null; } if (isset($t[1])) { $t[1] = trim(preg_replace('|[\\(\\)]|is', '', $t[1])); $t[1] = str_replace(',', '.', $t[1]); $char->fuel_consumption_combined_at = (double) $t[1] > 0 ? (double) $t[1] : null; } elseif (isset($char->transmission_at)) { $char->fuel_consumption_combined_at = $char->fuel_consumption_combined_mt; } } if (isset($tmp['Размер шин']) && ($t = preg_split('/(<br>)/iU', $tmp['Размер шин']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(str_ireplace(array("\n", '(', ')', 'Спереди', 'Сзади'), '', $t[0])); $char->tyres_front = $t[0] ? $t[0] : null; } if (isset($t[1])) { $t[1] = trim(str_ireplace(array("\n", '(', ')', 'Спереди', 'Сзади'), '', $t[1])); $char->tyres_rear = $t[1] ? $t[1] : null; } else { $char->tyres_rear = $char->tyres_front; } } if (isset($tmp['Размер дисков']) && ($t = preg_split('/(<br>)/iU', $tmp['Размер дисков']))) { $t = CArray::trimEmpty($t); if (isset($t[0])) { $t[0] = trim(str_ireplace(array("\n", '(', ')', 'Спереди', 'Сзади'), '', $t[0])); $char->disks_front = $t[0] ? $t[0] : null; } if (isset($t[1])) { $t[1] = trim(str_ireplace(array("\n", '(', ')', 'Спереди', 'Сзади'), '', $t[1])); $char->disks_rear = $t[1] ? $t[1] : null; } else { $char->disks_rear = $char->disks_front; } } @($char->drive = $tmp['Привод']); @($char->suspension_front = $tmp['Передних колес']); @($char->suspension_rear = $tmp['Задних колес']); @($char->brakes_front = $tmp['Передние']); @($char->brakes_rear = $tmp['Задние']); @($char->fuel_type = $tmp['Топливо']); @($char->fuel_capacity = intval($tmp['Емкость топливного бака, л']) ? intval($tmp['Емкость топливного бака, л']) : null); $models[$k]->char = $char; $this->saveChar($models[$k]); } }
/** * Returns the names of the time zones that are known for a specified country. * * If the country's code is not recognized for any reason, the entire list of the known time zone names is * returned. * * @param string $countryCode The two-letter code of the country, as provided by ISO 3166. * * @return CArrayObject The known time zone names for the country specified, of type `CUStringObject`. */ public static function knownNamesForCountry($countryCode) { assert('is_cstring($countryCode)', vs(isset($this), get_defined_vars())); $paNames = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $countryCode); $paNames = CMap::filter($paNames, "CTimeZone::isNameIcuCompatible"); $names = CArray::fromPArray($paNames); if (is_cmap($paNames) && !CArray::isEmpty($names)) { return oop_a($names); } else { return oop_a(self::knownNames()); } }
public function testRepeat() { $array = CArray::repeat("a", 5); $this->assertTrue(CArray::equals($array, CArray::fromElements("a", "a", "a", "a", "a"))); }
/** * Sends a message to the recipient(s). * * @param reference $failedAddresses **OPTIONAL. OUTPUT.** After the method is called with this parameter * provided, the parameter's value, which is of type `CArrayObject`, is an array containing the email addresses of * the recipients who failed to receive the message. * * @return int The number of recipients who have successfully received the message. */ public function send(&$failedAddresses = null) { assert('isset($this->m_swiftMailer) && isset($this->m_swiftMessage)', vs(isset($this), get_defined_vars())); assert('(isset($this->m_from) || isset($this->m_sender) || isset($this->m_returnAddress)) && ' . '(isset($this->m_to) || isset($this->m_cc) || isset($this->m_bcc))', vs(isset($this), get_defined_vars())); $message = $this->m_swiftMessage; if (isset($this->m_from)) { $message->setFrom($this->m_from); } if (isset($this->m_to)) { $message->setTo($this->m_to); } if (isset($this->m_cc)) { $message->setCc($this->m_cc); } if (isset($this->m_bcc)) { $message->setBcc($this->m_bcc); } if (isset($this->m_sender)) { $message->setSender($this->m_sender); } if (isset($this->m_returnAddress)) { $message->setReturnPath($this->m_returnAddress); } if (isset($this->m_replyAddress)) { $message->setReplyTo($this->m_replyAddress); } if (isset($this->m_body)) { if (CString::equals($this->m_bodyType, CMimeType::PLAIN_TEXT)) { $this->m_body = $this->maybeWrapText($this->m_body); } $message->setBody($this->m_body, $this->m_bodyType); } if (isset($this->m_altBodiesAndTypes)) { $len = CArray::length($this->m_altBodiesAndTypes); for ($i = 0; $i < $len; $i++) { $bodyAndType = $this->m_altBodiesAndTypes[$i]; $body = $bodyAndType[0]; $type = $bodyAndType[1]; if (CString::equals($type, CMimeType::PLAIN_TEXT)) { $body = $this->maybeWrapText($body); } $message->addPart($body, $type); } } $paFailedAddresses; $res = $this->m_swiftMailer->send($message, $paFailedAddresses); if (is_cmap($paFailedAddresses)) { $failedAddresses = oop_a(CArray::fromPArray($paFailedAddresses)); } $res = is_int($res) ? $res : 0; return $res; }
public function testFindScalar() { $array = CArrayObject::fromSplArray(CArray::fromElements("a", "b", "c", "d", "e")); $found = $array->findScalar("c"); $this->assertTrue($found); $foundAtPos; $found = $array->findScalar("d", $foundAtPos); $this->assertTrue($found); $this->assertTrue($foundAtPos == 3); $found = $array->findScalar("C"); $this->assertFalse($found); $found = $array->findScalar("f"); $this->assertFalse($found); // Special case. $array = new CArrayObject(); $found = $array->findScalar("a"); $this->assertFalse($found); }
/** * Returns all the values assigned to a specified long option with which the script was run, * e.g. "--option=value1 --option=value2". * * @param string $optionName The name of the option, excluding "-". * * @return CArrayObject The values of the option specified, where each value is of type `CUStringObject`. */ public static function valuesForLongOption($optionName) { assert('is_cstring($optionName)', vs(isset($this), get_defined_vars())); assert('self::hasLongOptionWithValue($optionName)', vs(isset($this), get_defined_vars())); $opt = getopt("", ["{$optionName}:"]); $values = $opt[$optionName]; return oop_a(is_cmap($values) ? CArray::fromPArray($values) : CArray::fromElements($values)); }
/** * @ignore */ public function __clone() { $this->m_components = CArray::makeCopy($this->m_components); }
public function leaveNode(PhpParser\Node $node) { if ($node->hasAttribute("_insertGetMMethodAfterMe") || $node->hasAttribute("_insertSetMMethodAfterMe")) { $statements = [$node]; if ($node->hasAttribute("_insertGetMMethodAfterMe")) { $subStatements = CMap::make(); $len = CArray::length($this->m_propsToWrap); for ($i = 0; $i < $len; $i++) { $propName = $this->m_propsToWrap[$i]; $subCondition = new PhpParser\Node\Expr\BooleanNot(new PhpParser\Node\Expr\FuncCall(new PhpParser\Node\Name(self::$ms_isFwCallFuncName))); $return0 = new PhpParser\Node\Stmt\Return_(new PhpParser\Node\Expr\PropertyFetch(new PhpParser\Node\Expr\Variable("this"), $propName)); $return1 = new PhpParser\Node\Stmt\Return_(new PhpParser\Node\Expr\FuncCall(new PhpParser\Node\Name(self::$ms_toOopFuncName), [new PhpParser\Node\Expr\PropertyFetch(new PhpParser\Node\Expr\Variable("this"), $propName)])); $else = new PhpParser\Node\Stmt\Else_([$return1]); $subIf = new PhpParser\Node\Stmt\If_($subCondition, ["stmts" => [$return0], "else" => $else]); $condition = new PhpParser\Node\Expr\BinaryOp\Identical(new PhpParser\Node\Expr\Variable("name"), new PhpParser\Node\Scalar\String($propName)); $if = new PhpParser\Node\Stmt\If_($condition, ["stmts" => [$subIf]]); CMap::insertValue($subStatements, $if); } $method = new PhpParser\Node\Stmt\ClassMethod("__get", ["type" => PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC, "byRef" => true, "params" => [new PhpParser\Node\Param("name")], "stmts" => $subStatements]); CMap::insertValue($statements, $method); } if ($node->hasAttribute("_insertSetMMethodAfterMe")) { $subStatements = CMap::make(); $len = CArray::length($this->m_propsToWrap); for ($i = 0; $i < $len; $i++) { $propName = $this->m_propsToWrap[$i]; $subCondition = new PhpParser\Node\Expr\BooleanNot(new PhpParser\Node\Expr\FuncCall(new PhpParser\Node\Name(self::$ms_isFwCallFuncName))); $assignment0 = new PhpParser\Node\Expr\Assign(new PhpParser\Node\Expr\PropertyFetch(new PhpParser\Node\Expr\Variable("this"), $propName), new PhpParser\Node\Expr\Variable("value")); $assignment1 = new PhpParser\Node\Expr\Assign(new PhpParser\Node\Expr\PropertyFetch(new PhpParser\Node\Expr\Variable("this"), $propName), new PhpParser\Node\Expr\FuncCall(new PhpParser\Node\Name(self::$ms_fromOopFuncName), [new PhpParser\Node\Expr\Variable("value")])); $else = new PhpParser\Node\Stmt\Else_([$assignment1]); $subIf = new PhpParser\Node\Stmt\If_($subCondition, ["stmts" => [$assignment0], "else" => $else]); $condition = new PhpParser\Node\Expr\BinaryOp\Identical(new PhpParser\Node\Expr\Variable("name"), new PhpParser\Node\Scalar\String($propName)); $if = new PhpParser\Node\Stmt\If_($condition, ["stmts" => [$subIf]]); CMap::insertValue($subStatements, $if); } $method = new PhpParser\Node\Stmt\ClassMethod("__set", ["type" => PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC, "params" => [new PhpParser\Node\Param("name"), new PhpParser\Node\Param("value")], "stmts" => $subStatements]); CMap::insertValue($statements, $method); } return $statements; } }
?> </div> <?php $cities = City::getCitiesArray($this->getFilterValue('region_id')); } $objTypes = CArray::merge(array(0 => ''), ApartmentObjType::getList()); $typeList = CArray::merge(array(0 => ''), Apartment::getTypesArray()); ?> <div class=""> <div class=""><?php echo Yii::t('common', 'City'); ?> :</div> <?php $cities = isset($cities) && count($cities) ? $cities : CArray::merge(array(0 => tc('select city')), ApartmentCity::getAllCity()); echo CHtml::dropDownList('filter[city_id]', $this->getFilterValue('city_id'), $cities, array('class' => ' searchField', 'id' => 'ap_city')); ?> </div> <div class="rowold"> <div class=""><?php echo tc('Type'); ?> :</div> <?php echo CHtml::dropDownList('filter[type]', $this->getFilterValue('type'), $typeList); ?> </div> <div class="rowold">
/** * Determines if the keys in a map are all integer and sequential. * * Sequential keys are a sequence of integers that start with a `0` and go up, incrementing exactly by one. * * This method could be useful to see if a PHP's associative array (a map) can be naturally converted into a * regular array (SplFixedArray) when dealing with interfaces that are using the PHP's associative array in the * role of a regular array. * * As a special case, the method returns `true` for an empty map. * * @param map $map The map to be looked into. * * @return bool `true` if all keys in the map are integer and sequential, `false` otherwise. */ public static function areKeysSequential($map) { assert('is_cmap($map)', vs(isset($this), get_defined_vars())); $map = parray($map); $keys = self::keys($map); $len = CArray::length($keys); for ($i = 0; $i < $len; $i++) { if (!is_int($keys[$i]) || $keys[$i] != $i) { return false; } } return true; }
public static function getCountriesArray($type = 0, $all = 0) { // 0 - без первой строки, 1 - пустая первая строка, 2 - любой, 3 - не указан $active_str = $all ? '' : 'WHERE active = 1 '; $sql = 'SELECT id, name_' . Yii::app()->language . ' AS name FROM {{location_country}} ' . $active_str . 'ORDER BY sorter ASC'; $res = Yii::app()->db->createCommand($sql)->queryAll(); $res = CHtml::listData($res, 'id', 'name'); switch ($type) { case 1: $countries = CArray::merge(array(0 => ''), $res); break; case 2: $countries = CArray::merge(array(0 => tc('select country')), $res); break; case 3: $countries = CArray::merge(array(0 => tc('Not specified_f')), $res); break; default: $countries = $res; } return $countries; }
/** * Собирает все значения из многомерного массива не сохраняет ключи */ public static function collectValues($array, &$result = array()) { if (!is_array($array)) { $result[] = $array; return $array; } else { foreach ($array as $e) { CArray::collectValues($e, $result); } } return $result; }
protected function removeHeader($headerName) { $headerName = CString::trim($headerName); CArray::removeByValue($this->m_requestHeaders, $headerName, function ($element0, $element1) { return CRegex::find($element0, "/^\\h*" . CRegex::enterTd($element1) . "\\h*:/i"); }); }
/** * Splits a string into substrings using a specified pattern or patterns as the delimiter(s) and returns the * resulting strings as an array. * * If no delimiter patterns were found, the resulting array contains just one element, which is the original * string. If a delimiter is located at the very start or at the very end of the string or next to another * delimiter, it will accordingly cause some string(s) in the resulting array to be empty. * * As a special case, the delimiter pattern can be empty, which will split the string into its constituting * characters. * * @param string $string The string to be split. * @param string|array|map $delimiterPatternOrPatterns The pattern or array of patterns to be recognized as the * delimiter(s). * * @return CArray The resulting strings. */ public static function split($string, $delimiterPatternOrPatterns) { assert('is_cstring($string) && (is_cstring($delimiterPatternOrPatterns) || ' . 'is_collection($delimiterPatternOrPatterns))', vs(isset($this), get_defined_vars())); if (is_cstring($delimiterPatternOrPatterns)) { $numIdt = self::findGroups($delimiterPatternOrPatterns, "/^([^0-9A-Za-z\\s\\\\])(.*)\\1/", $foundGroups); assert('$numIdt == 2', vs(isset($this), get_defined_vars())); $idt = $foundGroups[1]; if (CString::isEmpty($idt)) { // Special case. if (CString::isEmpty($string)) { $resStrings = CArray::fromElements(""); return $resStrings; } else { if (preg_match("/^([^0-9A-Za-z\\s\\\\])\\1[A-Za-z]*u[A-Za-z]*\\z/", $delimiterPatternOrPatterns) !== 1) { $resStrings = CArray::make(strlen($string)); for ($i = 0; $i < strlen($string); $i++) { $resStrings[$i] = $string[$i]; } return $resStrings; } else { return CUString::splitIntoChars($string); } } } $paResStrings = preg_split($delimiterPatternOrPatterns, $string); $qty = count($paResStrings); $resStrings = CArray::make($qty); for ($i = 0; $i < $qty; $i++) { $resStrings[$i] = $paResStrings[$i]; } return $resStrings; } else { $resStrings = CArray::fromElements($string); foreach ($delimiterPatternOrPatterns as $delimiterPattern) { assert('is_cstring($delimiterPattern)', vs(isset($this), get_defined_vars())); $resStringsNew = CArray::make(); $len = CArray::length($resStrings); for ($i = 0; $i < $len; $i++) { CArray::pushArray($resStringsNew, self::split($resStrings[$i], $delimiterPattern)); } $resStrings = $resStringsNew; } return $resStrings; } }
/** * Normalizes a path by removing any trailing slashes, any redundant slashes, any references to the current * directory, and any references to the parent directory where possible, and returns the new path. * * For example, "/path//./dir-a/.././to//../dir-b/" is normalized to "/path/dir-b". * * @param string $path The path to be normalized (can be absolute or relative). * @param bool $targetIsExecutable **OPTIONAL. Default is** `false`. Tells whether the path's target should be * treated as an executable so that, if the path starts with ".", the resulting path will start with "." too and * the "." will not be removed as a reference to the current directory. * * @return CUStringObject The normalized path. */ public static function normalize($path, $targetIsExecutable = false) { assert('is_cstring($path) && is_bool($targetIsExecutable)', vs(isset($this), get_defined_vars())); assert('!CString::isEmpty($path)', vs(isset($this), get_defined_vars())); $path = CRegex::replace($path, "/\\/{2,}/", "/"); // normalize consecutive slashes $path = CString::stripEnd($path, "/"); // remove the trailing slash, if any if (CString::isEmpty($path)) { return "/"; } $path = CRegex::remove($path, "/\\/\\.(?=\\/|\\z)/"); // remove any "/." followed by a slash or at the end if (CString::isEmpty($path)) { return "/"; } if (!$targetIsExecutable) { $path = CString::stripStart($path, "./"); } $pathIsAbsolute; if (!CString::startsWith($path, "/")) { $pathIsAbsolute = false; } else { $pathIsAbsolute = true; $path = CString::substr($path, 1); } if (!CString::find($path, "/")) { if ($pathIsAbsolute) { if (!CString::equals($path, "..")) { $path = "/{$path}"; } else { $path = "/"; } } return $path; } // Recompose the path. $components = CString::split($path, "/"); $newComponents = CArray::make(); $len = CArray::length($components); for ($i = 0; $i < $len; $i++) { $comp = $components[$i]; $lastAddedComp = ""; $noCompsAddedYet = CArray::isEmpty($newComponents); if (!$noCompsAddedYet) { $lastAddedComp = CArray::last($newComponents); } if (CString::equals($comp, "..")) { if ($noCompsAddedYet || CString::equals($lastAddedComp, "..") || CString::equals($lastAddedComp, ".")) { if (!($noCompsAddedYet && $pathIsAbsolute)) { CArray::push($newComponents, $comp); } } else { CArray::pop($newComponents); } } else { CArray::push($newComponents, $comp); } } $path = CArray::join($newComponents, "/"); if ($pathIsAbsolute) { $path = "/{$path}"; } else { if (CString::isEmpty($path)) { $path = "."; } } return $path; }
public function testSplit() { // ASCII. $res = CRegex::split("He,llo;th,ere!", "/[,;]/"); $this->assertTrue(CArray::length($res) == 4 && CString::equals($res[0], "He") && CString::equals($res[1], "llo") && CString::equals($res[2], "th") && CString::equals($res[3], "ere!")); $res = CRegex::split("He,llo;th.ere!", CArray::fromElements("/[,;]/", "/\\./")); $this->assertTrue(CArray::length($res) == 4 && CString::equals($res[0], "He") && CString::equals($res[1], "llo") && CString::equals($res[2], "th") && CString::equals($res[3], "ere!")); // Special cases. $res = CRegex::split("", "/[,;]/"); $this->assertTrue(CArray::length($res) == 1 && CString::equals($res[0], "")); $res = CRegex::split("Hey", "//"); $this->assertTrue(CArray::length($res) == 3 && CString::equals($res[0], "H") && CString::equals($res[1], "e") && CString::equals($res[2], "y")); $res = CRegex::split("", "//"); $this->assertTrue(CArray::length($res) == 1 && CString::equals($res[0], "")); // Unicode. $res = CRegex::split("¡He,llo·se,ñor!", "/[,·]/u"); $this->assertTrue(CArray::length($res) == 4 && CUString::equals($res[0], "¡He") && CUString::equals($res[1], "llo") && CUString::equals($res[2], "se") && CUString::equals($res[3], "ñor!")); $res = CRegex::split("¡He,llo·se.ñor!", CArray::fromElements("/[,·]/u", "/\\./u")); $this->assertTrue(CArray::length($res) == 4 && CUString::equals($res[0], "¡He") && CUString::equals($res[1], "llo") && CUString::equals($res[2], "se") && CUString::equals($res[3], "ñor!")); // Special cases. $res = CRegex::split("", "/[,·]/u"); $this->assertTrue(CArray::length($res) == 1 && CUString::equals($res[0], "")); $res = CRegex::split("Héy", "//u"); $this->assertTrue(CArray::length($res) == 3 && CUString::equals($res[0], "H") && CUString::equals($res[1], "é") && CUString::equals($res[2], "y")); $res = CRegex::split("", "//u"); $this->assertTrue(CArray::length($res) == 1 && CUString::equals($res[0], "")); }
/** * Insert a row * @param string $table * @param array $aValues Array of couple field => value * @return mixed */ public function insert($table, $aValues) { $table = $this->quoteTable($table); $values = $this->quoteArray(array_values($aValues)); $sql = "\n INSERT INTO {$table}\n "; if (CArray::isAssoc($aValues)) { $field = array_keys($aValues); foreach ($field as &$f) { $f = $this->quoteField($f); } $sql .= " (" . implode(", ", $field) . ")"; } $sql .= " VALUES (" . implode(", ", $values) . ")"; $this->query($sql); return $this->getLastInsertedId(); }
protected static function recurseValueBeforeFiltering($value, $inputFilterOrFilterCollection, &$success, $currDepth) { assert('$inputFilterOrFilterCollection instanceof CInputFilter || ' . 'is_collection($inputFilterOrFilterCollection)', vs(isset($this), get_defined_vars())); if ($currDepth == self::$ms_maxRecursionDepth) { $success = false; return; } $currDepth++; if (!is_cmap($value)) { // Only interested in PHP arrays. return $value; } if (is_carray($inputFilterOrFilterCollection)) { // The output value is expected to be a CArray; the keys in the arrived PHP array should be sequential. if (!CMap::areKeysSequential($value)) { $success = false; return; } $value = CArray::fromPArray($value); $len = CArray::length($value); if ($len != CArray::length($inputFilterOrFilterCollection)) { $success = false; return; } for ($i = 0; $i < $len; $i++) { $inputValue = $value[$i]; $inputFilterElement = $inputFilterOrFilterCollection[$i]; $inputValue = self::recurseValueBeforeFiltering($inputValue, $inputFilterElement, $success, $currDepth); if (!$success) { return; } $value[$i] = $inputValue; } } else { if (is_cmap($inputFilterOrFilterCollection)) { // The output value is expected to be a CMap; already got one. foreach ($value as $inputKey => &$inputValue) { if (!CMap::hasKey($inputFilterOrFilterCollection, $inputKey)) { $success = false; return; } $inputFilterElement = $inputFilterOrFilterCollection[$inputKey]; $inputValue = self::recurseValueBeforeFiltering($inputValue, $inputFilterElement, $success, $currDepth); if (!$success) { return; } } unset($inputValue); } else { $success = false; return; } } return $value; }
public function process($image, $actions, $dir, $file, $render = FALSE) { // Set the "create" function switch ($image['type']) { case IMAGETYPE_JPEG: $create = 'imagecreatefromjpeg'; break; case IMAGETYPE_GIF: $create = 'imagecreatefromgif'; break; case IMAGETYPE_PNG: $create = 'imagecreatefrompng'; break; } // Set the "save" function switch (strtolower(substr(strrchr($file, '.'), 1))) { case 'jpg': case 'jpeg': $save = 'imagejpeg'; break; case 'gif': $save = 'imagegif'; break; case 'png': $save = 'imagepng'; break; } // Make sure the image type is supported for import if (empty($create) or !function_exists($create)) { throw new CException('image type not allowed'); } // Make sure the image type is supported for saving if (empty($save) or !function_exists($save)) { throw new CException('image type not allowed'); } // Load the image $this->image = $image; // Create the GD image resource $this->tmp_image = $create($image['file']); // Get the quality setting from the actions $quality = CArray::remove('quality', $actions); if ($status = $this->execute($actions)) { // Prevent the alpha from being lost imagealphablending($this->tmp_image, TRUE); imagesavealpha($this->tmp_image, TRUE); switch ($save) { case 'imagejpeg': // Default the quality to 95 $quality === NULL and $quality = 95; break; case 'imagegif': // Remove the quality setting, GIF doesn't use it unset($quality); break; case 'imagepng': // Always use a compression level of 9 for PNGs. This does not // affect quality, it only increases the level of compression! $quality = 9; break; } if ($render === FALSE) { // Set the status to the save return value, saving with the quality requested $status = isset($quality) ? $save($this->tmp_image, $dir . $file, $quality) : $save($this->tmp_image, $dir . $file); } else { // Output the image directly to the browser switch ($save) { case 'imagejpeg': header('Content-Type: image/jpeg'); break; case 'imagegif': header('Content-Type: image/gif'); break; case 'imagepng': header('Content-Type: image/png'); break; } $status = isset($quality) ? $save($this->tmp_image, NULL, $quality) : $save($this->tmp_image); } // Destroy the temporary image imagedestroy($this->tmp_image); } return $status; }
/** * Because PHP does not have this function, and array_walk_recursive creates * references in arrays and is not truly recursive. * * @param mixed callback to apply to each member of the array * @param array array to map to * @return array */ public static function map_recursive($callback, array $array) { foreach ($array as $key => $val) { // Map the callback to the key $array[$key] = is_array($val) ? CArray::map_recursive($callback, $val) : call_user_func($callback, $val); } return $array; }
/** * Determines if a locale name is valid and known. * * Scripts, variants, and keyword-value pairs are ignored. * * @param string $localeName The locale name to be looked into. * * @return bool `true` if the locale name is valid and known, `false` otherwise. */ public static function isValid($localeName) { assert('is_cstring($localeName)', vs(isset($this), get_defined_vars())); if (!CRegex::findGroups($localeName, "/^([a-z]{2,3}(?![^_\\-]))(?|[_\\-]([a-z]{2,3}(?![^_\\-]))|[_\\-][a-z]{4}(?![^_\\-])[_\\-]([a-z]{2,3}" . "(?![^_\\-]))|(?:\\z|[_\\-][a-z])).*\\z(?<=[a-z0-9])/i", $foundGroups)) { return false; } $rfc2616 = $foundGroups[0]; if (CArray::length($foundGroups) > 1) { $rfc2616 .= "-" . $foundGroups[1]; } return is_cstring(Locale::acceptFromHttp($rfc2616)); }
echo CHtml::label($model->getAttributeLabel('userType'), 'userType'); echo $form->dropDownList($model, 'type', CArray::merge(array(0 => tc('Please select')), User::getTypeList()), array('id' => 'userType')); ?> <?php echo CHtml::label($model->getAttributeLabel('withListings'), 'withListings'); echo $form->dropDownList($model, 'withListings', CArray::merge(array('' => tc('Please select')), array(0 => tc('No'), 1 => tc('Ok'))), array('id' => 'withListings')); ?> <?php if (issetModule('location')) { echo CHtml::label($model->getAttributeLabel('countryListing'), 'countryListing'); echo CHtml::dropDownList('Mailing[countryListing]', isset($this->selectedCountry) ? $this->selectedCountry : '', Country::getCountriesArray(2), array('class' => 'width285 searchField', 'id' => 'countryListing', 'ajax' => array('type' => 'GET', 'url' => $this->createUrl('/location/main/getRegions'), 'data' => 'js:"country="+$("#countryListing").val()+"&type=2"', 'success' => 'function(result){ $("#regionListing").html(result); $("#regionListing").change(); }'))); echo CHtml::label($model->getAttributeLabel('regionListing'), 'regionListing'); echo CHtml::dropDownList('Mailing[regionListing]', isset($this->selectedRegion) ? $this->selectedRegion : '', Region::getRegionsArray(isset($this->selectedCountry) ? $this->selectedCountry : 0, 2), array('class' => 'width285 searchField', 'id' => 'regionListing', 'ajax' => array('type' => 'GET', 'url' => $this->createUrl('/location/main/getCities'), 'data' => 'js:"region="+$("#regionListing").val()+"&type=2"', 'success' => 'function(result){ $("#cityListing").html(result); $("#cityListing").change(); }'))); } ?> <?php echo CHtml::label($model->getAttributeLabel('cityListing'), 'cityListing'); echo CHtml::dropDownList('Mailing[cityListing]', isset($this->selectedCity) ? $this->selectedCity : '', issetModule('location') ? City::getCitiesArray(isset($this->selectedRegion) ? $this->selectedRegion : 0, 2) : CArray::merge(array(0 => tc('select city')), ApartmentCity::getActiveCity()), array('class' => 'width285 searchField', 'id' => 'cityListing')); ?> <?php $this->endWidget();
echo $divClass; ?> "> <?php if ($this->searchShowLabel) { ?> <div class="<?php echo $textClass; ?> "><?php echo Yii::t('common', 'City'); ?> :</div> <?php } ?> <div class="<?php echo $controlClass; ?> "> <?php $cityArray = issetModule('location') && param('useLocation', 1) ? City::getCitiesArray(isset($this->selectedRegion) ? $this->selectedRegion : 0, 0) : $this->cityActive; if ($this->defaultTheme == 'atlas') { $cityArray = CArray::merge(array(0 => tc('select city')), $cityArray); } echo CHtml::dropDownList('city[]', isset($this->selectedCity) ? $this->selectedCity : '', $cityArray, array('class' => $fieldClass . ' width289 searchField')); //SearchForm::setJsParam('cityField', array('minWidth' => $minWidth)); // ?> </div> </li>
public static function getRegionsArray($country, $type = 0, $all = 0) { $active_str = $all ? '' : 'AND active = 1 '; if ($type != 4) { $sql = 'SELECT id, name_' . Yii::app()->language . ' AS name FROM {{location_region}} WHERE country_id = :country ' . $active_str . 'ORDER BY sorter ASC'; $res = Yii::app()->db->createCommand($sql)->queryAll(true, array(':country' => $country)); } else { $sql = 'SELECT id, name_' . Yii::app()->language . ' AS name FROM {{location_region}} ' . $active_str . 'ORDER BY sorter ASC'; $res = Yii::app()->db->createCommand($sql)->queryAll(); } $res = CHtml::listData($res, 'id', 'name'); switch ($type) { case 1: case 4: $regions = CArray::merge(array(0 => ''), $res); break; case 2: $regions = CArray::merge(array(0 => tc('select region')), $res); break; case 3: $regions = CArray::merge(array(0 => tc('Not specified_m')), $res); break; default: $regions = $res; } return $regions; }
/** * Splits a string into substrings using a specified substring or substrings as the delimiter(s) and returns the * resulting strings as an array. * * If no delimiter substrings were found, the resulting array contains just one element, which is the original * string. If a delimiter is located at the very start or at the very end of the string or next to another * delimiter, it will accordingly cause some string(s) in the resulting array to be empty. * * As a special case, the delimiter substring can be empty, which will split the string into its constituting * characters. * * @param string $string The string to be split. * @param string|array|map $delimiterOrDelimiters The substring or array of substrings to be recognized as the * delimiter(s). * * @return CArray The resulting strings. */ public static function split($string, $delimiterOrDelimiters) { assert('is_cstring($string) && ' . '(is_cstring($delimiterOrDelimiters) || is_collection($delimiterOrDelimiters))', vs(isset($this), get_defined_vars())); if (is_cstring($delimiterOrDelimiters)) { if (self::isEmpty($delimiterOrDelimiters)) { // Special case. if (self::isEmpty($string)) { $resStrings = CArray::fromElements(""); return $resStrings; } else { $resStrings = CArray::make(strlen($string)); for ($i = 0; $i < strlen($string); $i++) { $resStrings[$i] = $string[$i]; } return $resStrings; } } $resStrings = CArray::make(self::numSubstrings($string, $delimiterOrDelimiters) + 1); $startPos = 0; $i = 0; while (true) { $endPos = self::indexOf($string, $delimiterOrDelimiters, $startPos); if ($endPos != -1) { $resStrings[$i++] = self::substring($string, $startPos, $endPos); $startPos = $endPos + strlen($delimiterOrDelimiters); } else { $resStrings[$i] = self::substr($string, $startPos); break; } } return $resStrings; } else { $resStrings = CArray::fromElements($string); foreach ($delimiterOrDelimiters as $delimiter) { assert('is_cstring($delimiter)', vs(isset($this), get_defined_vars())); $resStringsNew = CArray::make(); $len = CArray::length($resStrings); for ($i = 0; $i < $len; $i++) { CArray::pushArray($resStringsNew, self::split($resStrings[$i], $delimiter)); } $resStrings = $resStringsNew; } return $resStrings; } }
/** * Starts a session by sending out the added requests. * * @param reference $success **OPTIONAL. OUTPUT.** After the method is called with this parameter provided, the * parameter's value tells whether the session was successful. * * @return void */ public function start(&$success = null) { $success = true; if ($this->m_hasError) { $success = false; return; } if (CArray::isEmpty($this->m_requestRecordsQueue)) { // Nothing to do. return; } // Current policy is to disable HTTP pipelining. $res = curl_multi_setopt($this->m_multiCurl, CURLMOPT_PIPELINING, 0); if (!$res) { // Should never get in here as long as cURL options are being set correctly, hence the assertion. assert('false', vs(isset($this), get_defined_vars())); $this->m_hasError = true; $this->m_errorMessage = "The 'curl_multi_setopt' function failed."; $success = false; $this->finalize(); return; } $anySuccessfulRequests = false; // Disable the script's execution timeout before getting into the session. $timeoutPause = new CTimeoutPause(); $numRunningRequests = 0; // also the index of the next request to send while (true) { // From the request queue, add as many normal cURL handles to the multi cURL handle as it is allowed by the // maximum number of concurrent requests, priorly setting internal options for every request. while ($numRunningRequests < CArray::length($this->m_requestRecordsQueue) && $numRunningRequests < $this->m_maxNumConcurrentRequests) { $requestRecord = $this->m_requestRecordsQueue[$numRunningRequests]; $request = $requestRecord[0]; $onCompleteCallback = $requestRecord[1]; $newCookieSession = $requestRecord[2]; $requestCurl = $request->curl(); // Set cURL options for the normal cURL handle, having created a temporary file for cookie storage if // needed. $requestSetOptSuccess; if ($this->m_cookiesAreEnabled && $request->isHttp()) { if (!isset($this->m_cookiesFp)) { $this->m_cookiesFp = CFile::createTemporary(); } $request->setInternalOptions($requestSetOptSuccess, $this->m_cookiesFp, $newCookieSession); } else { $request->setInternalOptions($requestSetOptSuccess); } if (!$requestSetOptSuccess) { if (isset($onCompleteCallback)) { call_user_func($onCompleteCallback, false, "", $request, $this); } CArray::remove($this->m_requestRecordsQueue, $numRunningRequests); continue; } // Add the normal cURL handle to the multi cURL handle. $res = curl_multi_add_handle($this->m_multiCurl, $requestCurl); if ($res != 0) { $this->m_hasError = true; $curlError = curl_multi_strerror($res); $this->m_errorMessage = is_cstring($curlError) && !CString::isEmpty($curlError) ? $curlError : "The 'curl_multi_add_handle' function failed."; $success = false; $timeoutPause->end(); $this->finalize(); return; } $numRunningRequests++; } if ($numRunningRequests == 0) { break; } // Process the currently added requests until complete or no more data is available. Although // `CURLM_CALL_MULTI_PERFORM` is deprecated since libcurl 7.20, keep it for compatibility reasons. $numRunningTransfers; do { $multiExecRes = curl_multi_exec($this->m_multiCurl, $numRunningTransfers); } while ($multiExecRes == CURLM_CALL_MULTI_PERFORM); if ($multiExecRes != CURLM_OK) { $this->m_hasError = true; $curlError = curl_multi_strerror($multiExecRes); $this->m_errorMessage = is_cstring($curlError) && !CString::isEmpty($curlError) ? $curlError : "The 'curl_multi_exec' function failed."; $success = false; $timeoutPause->end(); $this->finalize(); return; } // Check for completed requests, call the callback function for any completed one (if such a function is // defined), finalize completed requests, and remove completed requests from the queue. while (true) { $completedRequestInfo = curl_multi_info_read($this->m_multiCurl); if (!is_cmap($completedRequestInfo)) { break; } // A request has completed. assert('$completedRequestInfo["msg"] == CURLMSG_DONE', vs(isset($this), get_defined_vars())); $requestCurl = $completedRequestInfo["handle"]; $requestRes = $completedRequestInfo["result"]; $requestRecordPos; $found = CArray::find($this->m_requestRecordsQueue, $requestCurl, function ($requestRecord, $requestCurl) { $request = $requestRecord[0]; return $request->curl() == $requestCurl; }, $requestRecordPos); assert('$found', vs(isset($this), get_defined_vars())); $requestRecord = $this->m_requestRecordsQueue[$requestRecordPos]; $request = $requestRecord[0]; $onCompleteCallback = $requestRecord[1]; // Remove the normal cURL handle from the multi cURL handle. $res = curl_multi_remove_handle($this->m_multiCurl, $requestCurl); if ($res != 0) { $this->m_hasError = true; $curlError = curl_multi_strerror($res); $this->m_errorMessage = is_cstring($curlError) && !CString::isEmpty($curlError) ? $curlError : "The 'curl_multi_remove_handle' function failed."; $success = false; $timeoutPause->end(); $this->finalize(); return; } if ($requestRes == CURLE_OK) { // The request has succeeded. if (isset($onCompleteCallback)) { $response; if ($request->isReturnTransferSet()) { $response = curl_multi_getcontent($requestCurl); assert('is_cstring($response)', vs(isset($this), get_defined_vars())); } else { $response = ""; } $request->onRequestCompleteOk(); // also close the normal cURL handle call_user_func($onCompleteCallback, true, $response, $request, $this); } else { $request->onRequestCompleteOk(); // also close the normal cURL handle } $anySuccessfulRequests = true; } else { // The request has failed. $curlError = curl_strerror($requestRes); if (!is_cstring($curlError)) { $curlError = ""; } $request->onRequestCompleteWithError($curlError); // also close the normal cURL handle if (isset($onCompleteCallback)) { call_user_func($onCompleteCallback, false, "", $request, $this); } } CArray::remove($this->m_requestRecordsQueue, $requestRecordPos); $numRunningRequests--; } assert('$numRunningRequests == $numRunningTransfers', vs(isset($this), get_defined_vars())); if ($numRunningTransfers > 0) { // Some requests are still being processed (by remote machines). Wait for more data to appear on // sockets, without getting hard on the CPU. do { $multiSelectRes = curl_multi_select($this->m_multiCurl); } while ($multiSelectRes == -1); } else { // No requests are being processed. Check if any requests are pending. if (CArray::isEmpty($this->m_requestRecordsQueue)) { // No requests are pending. break; } } } // Set the script's execution time limit like the session has never happened. $timeoutPause->end(); if (!$anySuccessfulRequests) { $this->m_hasError = true; $this->m_errorMessage = "None of the session's requests succeeded."; $success = false; } $this->finalize(); }