Example #1
0
function getOrderWithAccountAndDeadline($accountEmail, $deadline)
{
    global $GetOrder_URL;
    $orders = array();
    $json = file_get_contents($GetOrder_URL);
    $data = json_decode($json, TRUE);
    $rows = $data['feed']['entry'];
    foreach ($rows as $item) {
        $account_email = $item['gsx$account']['$t'];
        $orderDeadline = $item['gsx$orderdeadline']['$t'];
        if ($orderDeadline === $deadline && (strlen($accountEmail) === 0 || $accountEmail == $account_email)) {
            $timeStamp = $item['gsx$timestamp']['$t'];
            $pickup = $item['gsx$pickup']['$t'];
            $vendor = $item['gsx$vendor']['$t'];
            $price = $item['gsx$price']['$t'];
            $remit = $item['gsx$remit']['$t'];
            $count = $item['gsx$count']['$t'];
            $remitRate = trim($remit);
            $remitRateFloat = floatVal($remitRate) / 100.0;
            //trim off % sign;
            $countInt = intVal($count);
            $price = trim($price);
            $price = substr($price, 1, strlen($price) - 1);
            $priceFloat = floatVal($price);
            array_push($orders, array($timeStamp, $account_email, $pickup, $vendor, $priceFloat, $remitRateFloat, $countInt));
        }
    }
    return $orders;
}
Example #2
0
function is_positive_int($num)
{
    $intNum = floor($num);
    $result = floatVal($num - $intNum);
    if ($result == 0) {
        return true;
    } else {
        return false;
    }
}
Example #3
0
 public function generateCoupon($type, $store = null)
 {
     $couponData = array();
     $couponData['name'] = 'Special Coupon ' . date('Y-m-d');
     $couponData['is_active'] = 1;
     // all websites here:
     $couponData['website_ids'] = array_keys(Mage::app()->getWebsites(true));
     $couponData['coupon_type'] = 2;
     // for mahento 1.4.1.1
     $couponData['coupon_code'] = strtoupper(uniqid());
     $maxUses = intVal(Mage::getStoreConfig('ambirth/' . $type . '/coupon_uses'));
     $usesPerCustomer = intVal(Mage::getStoreConfig('ambirth/' . $type . '/uses_per_customer'));
     $couponData['uses_per_coupon'] = $maxUses;
     $couponData['uses_per_customer'] = $usesPerCustomer;
     $couponData['from_date'] = '';
     //current date
     $days = intVal(Mage::getStoreConfig('ambirth/' . $type . '/coupon_days', $store));
     $date = date('Y-m-d', time() + $days * 24 * 3600);
     $couponData['to_date'] = $date;
     $couponData['simple_action'] = Mage::getStoreConfig('ambirth/' . $type . '/coupon_type', $store);
     $couponData['discount_amount'] = Mage::getStoreConfig('ambirth/' . $type . '/coupon_amount', $store);
     if ('ampromo_cart' == $couponData['simple_action']) {
         $couponData['promo_sku'] = $couponData['discount_amount'];
         $couponData['discount_amount'] = 0;
     }
     $couponData['conditions'] = array('1' => array('type' => 'salesrule/rule_condition_combine', 'aggregator' => 'all', 'value' => 1, 'new_child' => ''), '1--1' => array('type' => 'salesrule/rule_condition_address', 'attribute' => 'base_subtotal', 'operator' => '>=', 'value' => floatVal(Mage::getStoreConfig('ambirth/' . $type . '/min_order', $store))));
     $couponData['actions'] = array(1 => array('type' => 'salesrule/rule_condition_product_combine', 'aggregator' => 'all', 'value' => 1, 'new_child' => ''));
     //compatibility with aitoc's individ promo module
     $couponData['customer_individ_ids'] = array();
     //create for all customer groups
     $couponData['customer_group_ids'] = array();
     if (!Mage::getStoreConfig('ambirth/' . $type . '/customer_group', $store)) {
         $customerGroups = Mage::getResourceModel('customer/group_collection')->load();
         $found = false;
         foreach ($customerGroups as $group) {
             if (0 == $group->getId()) {
                 $found = true;
             }
             $couponData['customer_group_ids'][] = $group->getId();
         }
         if (!$found) {
             $couponData['customer_group_ids'][] = 0;
         }
     } else {
         $groups = Mage::getStoreConfig('ambirth/' . $type . '/customer_group', $store);
         $couponData['customer_group_ids'] = explode(',', $groups);
     }
     try {
         Mage::getModel('salesrule/rule')->loadPost($couponData)->save();
     } catch (Exception $e) {
         //print_r($e); exit;
         $couponData['coupon_code'] = '';
     }
     return $couponData['coupon_code'];
 }
Example #4
0
function ValorEnLetras($x, $Moneda ) 
{
    $s="";
    $Ent="";
    $Frc="";
    $Signo="";
        
    if(floatVal($x) < 0)
     $Signo = $this->Neg . " ";
    else
     $Signo = "";
    
    if(intval(number_format($x,2,'.','') )!=$x) //<- averiguar si tiene decimales
      $s = number_format($x,2,'.','');
    else
      $s = number_format($x,0,'.','');
       
    $Pto = strpos($s, $this->Dot);
        
    if ($Pto === false)
    {
      $Ent = $s;
      $Frc = $this->Void;
    }
    else
    {
      $Ent = substr($s, 0, $Pto );
      $Frc =  substr($s, $Pto+1);
    }

    if($Ent == $this->Zero || $Ent == $this->Void)
       $s = "Cero ";
    elseif( strlen($Ent) > 7)
    {
       $s = $this->SubValLetra(intval( substr($Ent, 0,  strlen($Ent) - 6))) . 
             "Millones " . $this->SubValLetra(intval(substr($Ent,-6, 6)));
    }
    else
    {
      $s = $this->SubValLetra(intval($Ent));
    }

    if (substr($s,-9, 9) == "Millones " || substr($s,-7, 7) == "Millón ")
       $s = $s . "de ";

    $s = $s . $Moneda;

    if($Frc != $this->Void)
    {
       $s = $s . " Con " . $this->SubValLetra(intval($Frc)) . "Centavos";
       //$s = $s . " " . $Frc . "/100";
    }
    return ($Signo . $s . " M.N.");
   
}
 function save_post($post_id)
 {
     if (get_post_type($post_id) != $this->slug) {
         return;
     }
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
         return;
     }
     if (isset($_POST['conferencer_nonce']) && !wp_verify_nonce($_POST['conferencer_nonce'], plugin_basename(__FILE__))) {
         return;
     }
     if (!current_user_can('edit_post', $post_id)) {
         return;
     }
     foreach ($this->options as $key => $option) {
         if ($option['type'] == 'internal') {
             continue;
         }
         if (isset($_POST['conferencer_' . $key])) {
             $value = deep_trim($_POST['conferencer_' . $key]);
         } else {
             $value = "";
         }
         if ($option['type'] == 'int') {
             $value = intval($value);
         }
         if ($option['type'] == 'money') {
             $value = floatVal($value);
         }
         if ($option['type'] == 'multi-select') {
             $values = array();
             if (isset($_POST['conferencer_' . $key])) {
                 foreach ($_POST['conferencer_' . $key] as $value) {
                     if (!empty($value)) {
                         $values[] = $value;
                     }
                 }
             }
             $value = $values;
         }
         if ($option['type'] == 'date-time') {
             $value = 0;
             if (isset($_POST['conferencer_' . $key])) {
                 $date = getdate(strtotime($_POST['conferencer_' . $key]['date']));
                 $time = getdate(strtotime($_POST['conferencer_' . $key]['time']));
                 $value = mktime($time['hours'], $time['minutes'], $time['seconds'], $date['mon'], $date['mday'], $date['year']);
             }
         }
         update_post_meta($post_id, '_conferencer_' . $key, $value);
     }
 }
 public function checkDecimalAndPositive()
 {
     if (is_numeric($this->data[$this->alias]['marks'])) {
         $floatVal = floatVal($this->data[$this->alias]['marks']);
         if ($floatVal < 0) {
             return false;
         } else {
             // check if it has 1 decimal place at most
             if (fmod($floatVal * 10, 1) != 0) {
                 return false;
             }
         }
         return true;
     } else {
         return false;
     }
 }
Example #7
0
 public function __construct($conditions = [])
 {
     parent::__construct($conditions);
     // post processing
     foreach ($this->iterate() as &$curTpl) {
         $curTpl['spells'] = [];
         // [spellId, triggerType, charges, chanceOrPpm]
         for ($i = 1; $i <= 3; $i++) {
             if ($curTpl['object' . $i] <= 0) {
                 continue;
             }
             switch ($curTpl['type' . $i]) {
                 case 1:
                     $proc = -$this->getField('ppmRate') ?: ($this->getField('procChance') ?: $this->getField('amount' . $i));
                     $curTpl['spells'][$i] = [$curTpl['object' . $i], 2, $curTpl['charges'], $proc];
                     $this->relSpells[] = $curTpl['object' . $i];
                     break;
                 case 3:
                     $curTpl['spells'][$i] = [$curTpl['object' . $i], 1, $curTpl['charges'], 0];
                     $this->relSpells[] = $curTpl['object' . $i];
                     break;
                 case 7:
                     $curTpl['spells'][$i] = [$curTpl['object' . $i], 0, $curTpl['charges'], 0];
                     $this->relSpells[] = $curTpl['object' . $i];
                     break;
             }
         }
         // floats are fetched as string from db :<
         $curTpl['dmg'] = floatVal($curTpl['dmg']);
         $curTpl['dps'] = floatVal($curTpl['dps']);
         // remove zero-stats
         foreach (Util::$itemMods as $str) {
             if ($curTpl[$str] == 0) {
                 // empty(0.0f) => true .. yeah, sure
                 unset($curTpl[$str]);
             }
         }
         if ($curTpl['dps'] == 0) {
             unset($curTpl['dps']);
         }
     }
     if ($this->relSpells) {
         $this->relSpells = new SpellList(array(['id', $this->relSpells]));
     }
 }
 function convert_to_letter($x, $Moneda = '')
 {
     $s = "";
     $Ent = "";
     $Frc = "";
     $Signo = "";
     if (floatVal($x) < 0) {
         $Signo = $this->Neg . " ";
     } else {
         $Signo = "";
     }
     if (intval(number_format($x, 2, '.', '')) != $x) {
         //<- averiguar si tiene decimales
         $s = number_format($x, 2, '.', '');
     } else {
         $s = number_format($x, 2, '.', '');
     }
     $Pto = strpos($s, $this->Dot);
     if ($Pto === false) {
         $Ent = $s;
         $Frc = $this->Void;
     } else {
         $Ent = substr($s, 0, $Pto);
         $Frc = substr($s, $Pto + 1);
     }
     if ($Ent == $this->Zero || $Ent == $this->Void) {
         $s = "Cero ";
     } elseif (strlen($Ent) > 7) {
         $s = $this->SubValLetra(intval(substr($Ent, 0, strlen($Ent) - 6))) . "Millones " . $this->SubValLetra(intval(substr($Ent, -6, 6)));
     } else {
         $s = $this->SubValLetra(intval($Ent));
     }
     if (substr($s, -9, 9) == "Millones " || substr($s, -7, 7) == "Millón ") {
         $s = $s . "de ";
     }
     $s = $s . $Moneda;
     if ($Frc != $this->Void) {
         $s = $s . " " . $Frc . "/100";
         //$s = $s . " " . $Frc . "/100";
     }
     $letrass = $Signo . $s . "";
     return $Signo . $s . "";
 }
Example #9
0
 public function gini_impurity()
 {
     /*
      Returns the gini impurity score associated to the distribution in the node
     */
     $purity = floatval(0);
     if ($this->distribution == null) {
         return null;
     }
     foreach ($this->distribution as $distribution) {
         $purity += pow($distribution[1] / floatval($this->count), 2);
     }
     return (floatVal(1) - $purity) / 2;
 }
Example #10
0
 public static function SetMeetingParams($userId, $eventId, $arFields)
 {
     global $DB;
     $eventId = intVal($eventId);
     $userId = intVal($userId);
     // Check $arFields
     if (!in_array($arFields['ACCESSIBILITY'], array('busy', 'quest', 'free', 'absent'))) {
         $arFields['ACCESSIBILITY'] = 'busy';
     }
     $arReminders = array();
     if ($arFields['REMIND'] && is_array($arFields['REMIND'])) {
         foreach ($arFields['REMIND'] as $remind) {
             if (in_array($remind['type'], array('min', 'hour', 'day'))) {
                 $arReminders[] = array('type' => $remind['type'], 'count' => floatVal($remind['count']));
             }
         }
     }
     $arFields['REMIND'] = count($arReminders) > 0 ? serialize($arReminders) : '';
     // Reminding options
     $Event = CCalendarEvent::GetById($eventId);
     if (!$Event) {
         return false;
     }
     $path = CCalendar::GetPath($arFields['CAL_TYPE']);
     $path = CHTTP::urlDeleteParams($path, array("action", "sessid", "bx_event_calendar_request", "EVENT_ID"));
     $viewPath = CHTTP::urlAddParams($path, array('EVENT_ID' => $eventId));
     $remAgentParams = array('eventId' => $eventId, 'userId' => $userId, 'viewPath' => $viewPath, 'calendarType' => $Event["CAL_TYPE"], 'ownerId' => $Event["OWNER_ID"]);
     // 1. clean reminders
     CCalendar::RemoveAgent($remAgentParams);
     // 2. Set new reminders
     foreach ($arReminders as $reminder) {
         $delta = intVal($reminder['count']) * 60;
         //Minute
         if ($reminder['type'] == 'hour') {
             $delta = $delta * 60;
         } elseif ($reminder['type'] == 'day') {
             $delta = $delta * 60 * 24;
         }
         //Day
         if ($Event['DT_FROM_TS'] - $delta >= time() - 60 * 5) {
             // Inaccuracy - 5 min
             CCalendar::AddAgent(CCalendar::Date($Event['DT_FROM_TS'] - $delta), $remAgentParams);
         }
     }
     // Select meeting info about event
     $res = CCalendarEvent::GetList(array('arFilter' => array("ID" => $eventId, "DELETED" => "N"), 'parseRecursion' => false));
     if ($Event = $res[0]) {
         if ($Event['IS_MEETING']) {
             // Try to find this user into attendees for this event
             $strSql = "SELECT * FROM b_calendar_attendees WHERE USER_KEY={$userId} AND EVENT_ID={$eventId}";
             $dbAtt = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             if ($att = $dbAtt->Fetch()) {
                 //Set params
                 $strSql = "UPDATE b_calendar_attendees SET " . $DB->PrepareUpdate("b_calendar_attendees", $arFields) . " WHERE EVENT_ID=" . $eventId . " AND USER_KEY=" . $userId;
                 $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             }
         }
     }
     CCalendar::ClearCache('attendees_list');
     return true;
 }
Example #11
0
 /** Get row evolution for a multiple labels */
 private function getMultiRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $labels, $segment, $column, $language = false)
 {
     $actualLabels = array();
     $metadata = $this->getRowEvolutionMetaData($idSite, $period, $date, $apiModule, $apiAction, $segment, $language);
     if (!isset($metadata['metrics'][$column])) {
         // invalid column => use the first one that's available
         $column = reset(array_keys($metadata['metrics']));
     }
     // load the tables for each label
     $dataTablesPerLabel = array();
     $dataTableMetadata = false;
     foreach ($labels as $labelIndex => $label) {
         $dataTable = $this->loadRowEvolutionData($idSite, $period, $date, $apiModule, $apiAction, $label, $segment);
         $dataTablesPerLabel[$labelIndex] = $dataTable->getArray();
         if (!$dataTableMetadata) {
             $dataTableMetadata = $dataTable->metadata;
         }
         $urlFound = false;
         foreach ($dataTablesPerLabel[$labelIndex] as $table) {
             if ($table->getRowsCount() > 0) {
                 $firstRow = $table->getFirstRow();
                 // in case labels were replaced in the data table (e.g. for browsers report),
                 // display the label from the table, not the one passed as filter
                 $columnLabel = $firstRow->getColumn('label');
                 if (!empty($columnLabel)) {
                     $actualLabels[$labelIndex] = $columnLabel;
                     // TODO: confirm we need this
                     // special case: websites report
                     //if ($apiAction == 'getWebsites')
                     //{
                     //	$actualLabels[$labelIndex] = html_entity_decode($actualLabels[$labelIndex]);
                     //}
                 }
                 // if url is available as metadata, use it (only for actions reports)
                 if ($url = $firstRow->getMetadata('url')) {
                     $actualLabels[$labelIndex] = $url;
                     $urlFound = true;
                 }
                 break;
             }
         }
         if (!$urlFound) {
             // if we have a recursive label and no url, use the path
             $actualLabels[$labelIndex] = str_replace(Piwik_API_DataTableLabelFilter::SEPARATOR_RECURSIVE_LABEL, ' - ', $label);
         }
     }
     // combine the tables
     $dataTable = new Piwik_DataTable_Array();
     $dataTable->setKeyName($dataTable->getKeyName());
     $dataTable->metadata = $dataTableMetadata;
     foreach (array_keys(reset($dataTablesPerLabel)) as $dateLabel) {
         $newRow = new Piwik_DataTable_Row();
         foreach ($dataTablesPerLabel as $labelIndex => $tableArray) {
             $table = $tableArray[$dateLabel];
             if ($table->getRowsCount() == 0) {
                 $value = 0;
             } else {
                 $value = $table->getFirstRow()->getColumn($column);
                 $value = floatVal(str_replace(',', '.', $value));
                 if ($value == '') {
                     $value = 0;
                 }
             }
             // keep metric in the label so that unit (%, s, ...) can be guessed correctly
             $label = $column . '_' . $labelIndex;
             $newRow->addColumn($label, $value);
         }
         $newTable = new Piwik_DataTable();
         $newTable->addRow($newRow);
         $dataTable->addTable($newTable, $dateLabel);
     }
     // the available metrics for the report are returned as metadata / availableColumns
     $metadata['availableColumns'] = $metadata['metrics'];
     // metadata / metrics should document the rows that are compared
     // this way, UI code can be reused
     $metadata['metrics'] = array();
     foreach ($actualLabels as $labelIndex => $label) {
         $label .= ' (' . $metadata['availableColumns'][$column] . ')';
         $metadata['metrics'][$column . '_' . $labelIndex] = $label;
     }
     $this->enhanceRowEvolutionMetaData($metadata, $dataTable);
     return array('column' => $column, 'data' => $dataTable, 'metadata' => $metadata);
 }
Example #12
0
$arHeaders = array(array("id" => "USER_ID", "content" => "ID", "sort" => "USER_ID"), array("id" => "BUYER", "content" => GetMessage("BUYER_ROW_BUYER"), "sort" => "NAME", "default" => true), array("id" => "LOGIN", "content" => GetMessage("BUYER_ROW_LOGIN"), "sort" => "LOGIN"), array("id" => "LAST_NAME", "content" => GetMessage("BUYER_ROW_LAST"), "sort" => "LAST_NAME"), array("id" => "NAME", "content" => GetMessage("BUYER_ROW_NAME"), "sort" => "NAME"), array("id" => "SECOND_NAME", "content" => GetMessage("BUYER_ROW_SECOND"), "sort" => "SECOND_NAME"), array("id" => "EMAIL", "content" => GetMessage("BUYER_ROW_MAIL"), "sort" => "EMAIL", "default" => true), array("id" => "PERSONAL_PHONE", "content" => GetMessage("BUYER_ROW_PHONE"), "sort" => "PERSONAL_PHONE", "default" => true), array("id" => "LAST_LOGIN", "content" => GetMessage('BUYER_ROW_LAST_LOGIN'), "sort" => "LAST_LOGIN", "default" => false), array("id" => "DATE_REGISTER", "content" => GetMessage('BUYER_ROW_DATE_REGISTER'), "sort" => "DATE_REGISTER", "default" => true), array("id" => "LAST_ORDER_DATE", "content" => GetMessage('BUYER_ROW_LAST_ORDER_DATE'), "sort" => "LAST_ORDER_DATE", "default" => true), array("id" => "ORDER_COUNT", "content" => GetMessage('BUYER_ROW_COUNT_ORDER'), "sort" => "ORDER_COUNT", "default" => true, "align" => "right"), array("id" => "ORDER_SUM", "content" => GetMessage('BUYER_ROW_SUM_ORDER'), "sort" => "ORDER_SUM", "default" => true, "align" => "right"), array("id" => "GROUPS_ID", "content" => GetMessage('BUYER_ROW_GROUP')));
$lAdmin->AddHeaders($arHeaders);
$arVisibleColumns = $lAdmin->GetVisibleHeaderColumns();
$arOrderBuyer[$by] = $order;
$dbUsersList = CSaleUser::GetBuyersList($arOrderBuyer, $arFilter, false, array("nPageSize" => CAdminResult::GetNavSize($sTableID)), array("ID", "LID", "ACTIVE", "DATE_REGISTER", "LOGIN", "EMAIL", "NAME", "LAST_NAME", "SECOND_NAME", "PERSONAL_PHONE", "USER_ID", "LAST_LOGIN", "ORDER_COUNT", "ORDER_SUM", "CURRENCY", "LAST_ORDER_DATE"));
$dbUsersList = new CAdminResult($dbUsersList, $sTableID);
$dbUsersList->NavStart();
$lAdmin->NavText($dbUsersList->GetNavPrint(GetMessage("BUYER_PRLIST")));
while ($arBuyers = $dbUsersList->Fetch()) {
    $row =& $lAdmin->AddRow($arBuyers["USER_ID"], $arBuyers, "sale_buyers_profile.php?USER_ID=" . $arBuyers["USER_ID"] . "&lang=" . LANGUAGE_ID, GetMessage("BUYER_SUB_ACTION_PROFILE"));
    $profile = '<a href="sale_buyers_profile.php?USER_ID=' . $arBuyers["USER_ID"] . '&lang=' . LANGUAGE_ID . '">' . $arBuyers["USER_ID"] . '</a>';
    $row->AddField("USER_ID", $profile);
    if (floatVal($arBuyers["ORDER_SUM"]) > 0 && in_array("ORDER_SUM", $arVisibleColumns)) {
        $row->AddField("ORDER_SUM", SaleFormatCurrency($arBuyers["ORDER_SUM"], $arBuyers["CURRENCY"]));
    }
    if (floatVal($arBuyers["ORDER_COUNT"]) <= 0) {
        $row->AddField("ORDER_COUNT", '&nbsp;');
    }
    if (in_array("GROUPS_ID", $arVisibleColumns)) {
        $strUserGroup = '';
        $arUserGroups = CUser::GetUserGroup($arBuyers["USER_ID"]);
        foreach ($arUsersGroups as $arGroup) {
            if (in_array($arGroup["ID"], $arUserGroups)) {
                $strUserGroup .= htmlspecialcharsbx($arGroup["NAME"]) . "<br>";
            }
        }
        $row->AddField("GROUPS_ID", $strUserGroup);
    }
    if (in_array("LID", $arVisibleColumns)) {
        $row->AddField("LID", $arSites[$arBuyers["LID"]]["NAME"]);
    }
Example #13
0
 private function _initRule($rule, $address, $quote)
 {
     $types = array(Amasty_Rules_Helper_Data::TYPE_XY_PERCENT, Amasty_Rules_Helper_Data::TYPE_XY_FIXED);
     if (in_array($rule->getSimpleAction(), $types)) {
         return $this->_initRuleXY($rule, $address, $quote);
     }
     $r = array();
     $prices = $this->_getSortedCartPices($rule, $address);
     if (!$prices) {
         return $r;
     }
     $qty = $this->_getQty($rule, count($prices));
     if ($qty < 1) {
         return $r;
     }
     $step = (int) $rule->getDiscountStep();
     if ($rule->getSimpleAction() == Amasty_Rules_Helper_Data::TYPE_CHEAPEST) {
         $prices = array_slice($prices, 0, $qty);
     } elseif ($rule->getSimpleAction() == Amasty_Rules_Helper_Data::TYPE_EXPENCIVE) {
         $prices = array_slice($prices, -$qty, $qty);
     } elseif ($rule->getSimpleAction() == Amasty_Rules_Helper_Data::TYPE_EACH_N) {
         $prices = array_reverse($prices);
         // now it is from  big to small (80, 50, 50, 30 ...)
     }
     $percentage = floatVal($rule->getDiscountAmount());
     if (!$percentage) {
         $percentage = 100;
     }
     $percentage = $percentage / 100.0;
     $lastId = -1;
     $currQty = 0;
     // for each N we need to limit Max applied qty also
     foreach ($prices as $i => $price) {
         // skip items beside each, say 3-d, depends on the $step
         $types = array(Amasty_Rules_Helper_Data::TYPE_EACH_N, Amasty_Rules_Helper_Data::TYPE_FIXED);
         if (in_array($rule->getSimpleAction(), $types) && $step > 1 && ($i + 1) % $step) {
             continue;
         }
         // introduce limit for each N with discount or each N with fixed.
         if ($currQty >= $qty) {
             continue;
         }
         ++$currQty;
         $discount = $price['price'] * $percentage;
         $baseDiscount = $price['base_price'] * $percentage;
         if ($rule->getSimpleAction() == Amasty_Rules_Helper_Data::TYPE_FIXED) {
             $discount = $price['price'] - $quote->getStore()->convertPrice($rule->getDiscountAmount());
             $baseDiscount = $price['base_price'] - $rule->getDiscountAmount();
         }
         if ($price['id'] != $lastId) {
             $lastId = intVal($price['id']);
             $r[$lastId] = array();
             $r[$lastId]['discount'] = $discount;
             $r[$lastId]['base_discount'] = $baseDiscount;
         } else {
             $r[$lastId]['discount'] += $discount;
             $r[$lastId]['base_discount'] += $baseDiscount;
         }
     }
     return $r;
 }
Example #14
0
function siteconfig()
{
    if (!DB::isConnected(DB_AOWOW)) {
        CLISetup::log();
        CLISetup::log("database not yet set up!\n        Please use --dbconfig for setup", CLISetup::LOG_WARN);
        return;
    }
    while (true) {
        CLISetup::log();
        CLISetup::log('select a numerical index to use the corresponding entry');
        $results = DB::Aowow()->select('SELECT *, (flags & ?d) AS php FROM ?_config ORDER BY php ASC', CON_FLAG_PHP);
        $hasEmpty = false;
        foreach ($results as $idx => $data) {
            if (!($data['flags'] & CON_FLAG_PHP) && $data['value'] === '') {
                $hasEmpty = true;
            }
            $php = $data['flags'] & CON_FLAG_PHP;
            $buff = "[" . CLISetup::bold($idx) . "] " . ($idx > 9 ? '' : ' ') . ($php ? '  PHP   ' : ' AOWOW  ');
            $buff .= str_pad($php ? strtolower($data['key']) : strtoupper('cfg_' . $data['key']), 35);
            if ($data['value'] === '') {
                $buff .= CLISetup::red('<empty>');
            } else {
                $info = explode(' - ', $data['comment']);
                if ($data['flags'] & CON_FLAG_TYPE_BOOL) {
                    $buff .= '[bool] ' . ($data['value'] ? '<Enabled>' : '<Disabled>');
                } else {
                    if ($data['flags'] & CON_FLAG_OPT_LIST && !empty($info[2])) {
                        $buff .= "[opt]  ";
                        foreach (explode(', ', $info[2]) as $option) {
                            $opt = explode(':', $option);
                            $buff .= '[' . ($data['value'] == $opt[0] ? 'x' : ' ') . ']' . $opt[1] . ' ';
                        }
                    } else {
                        if ($data['flags'] & CON_FLAG_BITMASK && !empty($info[2])) {
                            $buff .= "[mask] ";
                            foreach (explode(', ', $info[2]) as $option) {
                                $opt = explode(':', $option);
                                $buff .= '[' . ($data['value'] & 1 << $opt[0] ? 'x' : ' ') . ']' . $opt[1] . ' ';
                            }
                        } else {
                            if ($data['flags'] & CON_FLAG_TYPE_STRING) {
                                $buff .= "[str]  " . $data['value'];
                            } else {
                                if ($data['flags'] & CON_FLAG_TYPE_FLOAT) {
                                    $buff .= "[float] " . floatVal($data['value']);
                                } else {
                                    /* if ($data['flags'] & CON_FLAG_TYPE_INT) */
                                    $buff .= "[int]  " . intVal($data['value']);
                                }
                            }
                        }
                    }
                }
            }
            CLISetup::log($buff);
        }
        CLISetup::log(str_pad("[" . CLISetup::bold(count($results)) . "]", 21) . "add another php configuration");
        if ($hasEmpty) {
            CLISetup::log();
            CLISetup::log("please configure the required empty setings", CLISetup::LOG_WARN);
        }
        $inp = ['idx' => ['', false, '/\\d/']];
        if (CLISetup::readInput($inp) && $inp && $inp['idx'] !== '') {
            // add new php setting
            if ($inp['idx'] == count($results)) {
                CLISetup::log();
                CLISetup::log("Adding additional php configuration.");
                while (true) {
                    $setting = array('key' => ['option name', false, '/[\\w_\\.\\-]/i'], 'val' => ['value']);
                    if (CLISetup::readInput($setting) && $setting) {
                        CLISetup::log();
                        $key = strtolower($setting['key']);
                        if (ini_get($key) === false || ini_set($key, $setting['val']) === false) {
                            CLISetup::log("this configuration option cannot be set", CLISetup::LOG_ERROR);
                            sleep(1);
                        } else {
                            if (DB::Aowow()->selectCell('SELECT 1 FROM ?_config WHERE `flags` & ?d AND `key` = ?', CON_FLAG_PHP, $key)) {
                                CLISetup::log("this configuration option is already in use", CLISetup::LOG_ERROR);
                                sleep(1);
                            } else {
                                DB::Aowow()->query('INSERT IGNORE INTO ?_config (`key`, `value`, `flags`) VALUES (?, ?, ?d)', $key, $setting['val'], CON_FLAG_TYPE_STRING | CON_FLAG_PHP);
                                CLISetup::log("new php configuration added", CLISetup::LOG_OK);
                                sleep(1);
                            }
                        }
                        break;
                    } else {
                        CLISetup::log();
                        CLISetup::log("edit canceled! returning to list...", CLISetup::LOG_WARN);
                        sleep(1);
                        break;
                    }
                }
            } else {
                if ($inp['idx'] >= 0 && $inp['idx'] < count($results)) {
                    $conf = $results[$inp['idx']];
                    $info = explode(' - ', $conf['comment']);
                    $buff = '';
                    CLISetup::log();
                    $buff .= $conf['flags'] & CON_FLAG_PHP ? "  PHP: " : "AOWOW: ";
                    $buff .= $conf['flags'] & CON_FLAG_PHP ? strtolower($conf['key']) : strtoupper('cfg_' . $conf['key']);
                    if (!empty($info[1])) {
                        $buff .= " - " . $info[1];
                    }
                    CLISetup::log($buff);
                    $buff = "VALUE: ";
                    if ($conf['flags'] & CON_FLAG_TYPE_BOOL) {
                        $buff .= $conf['value'] ? '<Enabled>' : '<Disabled>';
                    } else {
                        if ($conf['flags'] & CON_FLAG_OPT_LIST && !empty($info[2])) {
                            foreach (explode(', ', $info[2]) as $option) {
                                $opt = explode(':', $option);
                                $buff .= '[' . ($conf['value'] == $opt[0] ? 'x' : ' ') . '] ' . $opt[1] . ' ';
                            }
                        } else {
                            if ($conf['flags'] & CON_FLAG_BITMASK && !empty($info[2])) {
                                foreach (explode(', ', $info[2]) as $option) {
                                    $opt = explode(':', $option);
                                    $buff .= '[' . ($conf['value'] & 1 << $opt[0] ? 'x' : ' ') . '] ' . $opt[1] . ' ';
                                }
                            } else {
                                if ($conf['flags'] & CON_FLAG_TYPE_STRING) {
                                    $buff .= $conf['value'];
                                } else {
                                    if ($conf['flags'] & CON_FLAG_TYPE_FLOAT) {
                                        $buff .= floatVal($conf['value']);
                                    } else {
                                        /* if ($conf['flags'] & CON_FLAG_TYPE_INT) */
                                        $buff .= intVal($conf['value']);
                                    }
                                }
                            }
                        }
                    }
                    CLISetup::log($buff);
                    CLISetup::log();
                    CLISetup::log("[" . CLISetup::bold('E') . "]dit");
                    if (!($conf['flags'] & CON_FLAG_PERSISTENT)) {
                        CLISetup::log("[" . CLISetup::bold('D') . "]elete");
                    }
                    if (strstr($info[0], 'default:')) {
                        CLISetup::log("[" . CLISetup::bold('R') . "]estore Default - " . trim(explode('default:', $info[0])[1]));
                    }
                    while (true) {
                        $action = ['idx' => ['', true, '/[edr]/i']];
                        if (CLISetup::readInput($action, true) && $action) {
                            switch (strtoupper($action['idx'])) {
                                case 'E':
                                    // edit value
                                    $pattern = false;
                                    $single = false;
                                    $value = ['idx' => ['Select new value', false, &$pattern]];
                                    if ($conf['flags'] & CON_FLAG_OPT_LIST) {
                                        $_valid = [];
                                        foreach (explode(', ', $info[2]) as $option) {
                                            $opt = explode(':', $option);
                                            $_valid[] = $opt[0];
                                            CLISetup::log('[' . CLISetup::bold($opt[0]) . '] ' . $opt[1]);
                                        }
                                        $single = true;
                                        $pattern = '/\\d/';
                                        $validate = function ($v) use($_valid) {
                                            return in_array($v, $_valid);
                                        };
                                    } else {
                                        if ($conf['flags'] & CON_FLAG_BITMASK) {
                                            CLISetup::log('Bitmask: sum fields to select multiple options');
                                            $_valid = 0x0;
                                            foreach (explode(', ', $info[2]) as $option) {
                                                $opt = explode(':', $option);
                                                $_valid |= 1 << $opt[0];
                                                CLISetup::log('[' . CLISetup::bold(1 << $opt[0]) . ']' . str_pad('', 4 - strlen(1 << $opt[0])) . $opt[1]);
                                            }
                                            $pattern = '/\\d+/';
                                            $validate = function ($v) use($_valid) {
                                                $v = $v & $_valid;
                                                return $v;
                                            };
                                        } else {
                                            if ($conf['flags'] & CON_FLAG_TYPE_BOOL) {
                                                CLISetup::log('[' . CLISetup::bold(0) . '] Disabled');
                                                CLISetup::log('[' . CLISetup::bold(1) . '] Enabled');
                                                $single = true;
                                                $pattern = '/[01]/';
                                                $validate = function ($v) {
                                                    return true;
                                                };
                                            } else {
                                                if ($conf['flags'] & CON_FLAG_TYPE_INT) {
                                                    $validate = function ($v) {
                                                        return preg_match('/^-?\\d+$/i', $v);
                                                    };
                                                } else {
                                                    if ($conf['flags'] & CON_FLAG_TYPE_FLOAT) {
                                                        $validate = function ($v) {
                                                            return preg_match('/^-?\\d*(,|.)?\\d+$/i', $v);
                                                        };
                                                    } else {
                                                        // string
                                                        $validate = function ($v) {
                                                            return true;
                                                        };
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    while (true) {
                                        $use = $value;
                                        if (CLISetup::readInput($use, $single) && $use) {
                                            CLISetup::log();
                                            if (!$validate($use['idx'])) {
                                                CLISetup::log("value not in range", CLISetup::LOG_ERROR);
                                                sleep(1);
                                                continue;
                                            } else {
                                                DB::Aowow()->query('UPDATE ?_config SET `value` = ? WHERE `key` = ?', $use['idx'], strtolower($conf['key']));
                                                CLISetup::log("setting updated", CLISetup::LOG_OK);
                                                sleep(1);
                                                break 3;
                                            }
                                        } else {
                                            CLISetup::log("edit canceled! returning to selection...", CLISetup::LOG_WARN);
                                            sleep(1);
                                            break;
                                        }
                                    }
                                    break 2;
                                case 'R':
                                    // restore default
                                    if (!strstr($info[0], 'default:')) {
                                        continue 2;
                                    }
                                    // @eval .. some dafault values are supplied as bitmask or the likes
                                    if (DB::Aowow()->query('UPDATE ?_config SET `value` = ? WHERE `key` = ?', @eval('return (' . trim(explode('default:', $info[0])[1]) . ');'), strtolower($conf['key']))) {
                                        CLISetup::log("default value restored", CLISetup::LOG_OK);
                                        sleep(1);
                                    }
                                    break 2;
                                case 'D':
                                    // delete config pair
                                    if ($conf['flags'] & CON_FLAG_PERSISTENT) {
                                        continue 2;
                                    }
                                    if (DB::Aowow()->query('DELETE FROM ?_config WHERE `key` = ? AND (`flags` & ?d) = 0', strtolower($conf['key']), CON_FLAG_PERSISTENT)) {
                                        CLISetup::log("php setting deleted ['" . $conf['key'] . "': '" . $conf['value'] . "']", CLISetup::LOG_OK);
                                        sleep(1);
                                    }
                                    break 2;
                            }
                        } else {
                            CLISetup::log();
                            CLISetup::log("edit canceled! returning to list...", CLISetup::LOG_WARN);
                            sleep(1);
                            break;
                        }
                    }
                } else {
                    CLISetup::log();
                    CLISetup::log("invalid selection", CLISetup::LOG_ERROR);
                    sleep(1);
                }
            }
        } else {
            CLISetup::log();
            CLISetup::log("site configuration aborted", CLISetup::LOG_WARN);
            break;
        }
    }
}
 /**
  * {@inheritDoc}
  */
 public function loadCityData(ObjectManager $manager, $code)
 {
     $enabledLocale = $this->container->getParameter('enabled_locale');
     $locale = $this->container->getParameter('locale');
     $contentArray = array('ANDAU' => array(array('name' => 'CTY_ANDAU', 'translations' => array('field' => 'name', 'en_GB' => 'Andau', 'de_DE' => 'Andau'))), 'APETL' => array(array('name' => 'CTY_APETL', 'translations' => array('field' => 'name', 'en_GB' => 'Apetlon', 'de_DE' => 'Apetlon'))), 'KUKMI' => array(array('name' => 'CTY_KUKMI', 'translations' => array('field' => 'name', 'en_GB' => 'Kukmirn', 'de_DE' => 'Kukmirn'))), 'ARRIA' => array(array('name' => 'CTY_ARRIA', 'translations' => array('field' => 'name', 'en_GB' => 'Arriach', 'de_DE' => 'Arriach'))), 'GUTTA' => array(array('name' => 'CTY_GUTTA', 'translations' => array('field' => 'name', 'en_GB' => 'Guttaring', 'de_DE' => 'Guttaring'))), 'PREIT' => array(array('name' => 'CTY_PREIT', 'translations' => array('field' => 'name', 'en_GB' => 'Preitenegg', 'de_DE' => 'Preitenegg'))), 'LINZ' => array(array('name' => 'CTY_LINZ', 'translations' => array('field' => 'name', 'en_GB' => 'Linz', 'de_DE' => 'Linz'))), 'STEYR' => array(array('name' => 'CTY_STEYR', 'translations' => array('field' => 'name', 'en_GB' => 'Steyr', 'de_DE' => 'Steyr'))), 'WELS' => array(array('name' => 'CTY_WELS', 'translations' => array('field' => 'name', 'en_GB' => 'Wels', 'de_DE' => 'Wels'))), 'WAIDH' => array(array('name' => 'CTY_WAIDH', 'translations' => array('field' => 'name', 'en_GB' => 'Waidhofen an der Ybbs', 'de_DE' => 'Waidhofen an der Ybbs'))), 'KERMS' => array(array('name' => 'CTY_KERMS', 'translations' => array('field' => 'name', 'en_GB' => 'Krems an der Donau', 'de_DE' => 'Krems an der Donau'))), 'WIENR' => array(array('name' => 'CTY_WIENR', 'translations' => array('field' => 'name', 'en_GB' => 'Wiener Neustadt', 'de_DE' => 'Wiener Neustadt'))), 'MAISH' => array(array('name' => 'CTY_MAISH', 'translations' => array('field' => 'name', 'en_GB' => 'Maishofen', 'de_DE' => 'Maishofen'))), 'LOFER' => array(array('name' => 'CTY_LOFER', 'translations' => array('field' => 'name', 'en_GB' => 'Lofer', 'de_DE' => 'Lofer'))), 'ABERS' => array(array('name' => 'CTY_ABERS', 'translations' => array('field' => 'name', 'en_GB' => 'Abersee', 'de_DE' => 'Abersee'))), 'FEHRG' => array(array('name' => 'CTY_FEHRG', 'translations' => array('field' => 'name', 'en_GB' => 'Fehring', 'de_DE' => 'Fehring'))), 'GUNDE' => array(array('name' => 'CTY_GUNDE', 'translations' => array('field' => 'name', 'en_GB' => 'Gundersdorf', 'de_DE' => 'Gundersdorf'))), 'ADMOT' => array(array('name' => 'CTY_ADMOT', 'translations' => array('field' => 'name', 'en_GB' => 'Admont', 'de_DE' => 'Admont'))), 'GUNDE' => array(array('name' => 'CTY_GUNDE', 'translations' => array('field' => 'name', 'en_GB' => 'Gundersdorf', 'de_DE' => 'Gundersdorf'))), 'FEHRG' => array(array('name' => 'CTY_FEHRG', 'translations' => array('field' => 'name', 'en_GB' => 'Fehring', 'de_DE' => 'Fehring'))), 'BLP' => array(array('name' => 'CTY_BLP', 'translations' => array('field' => 'name', 'en_GB' => 'Belp', 'de_DE' => 'Belp'))), 'AHOR' => array(array('name' => 'CTY_AHOR', 'translations' => array('field' => 'name', 'en_GB' => 'Ahorn', 'de_DE' => 'Ahorn'))), 'BLP' => array(array('name' => 'CTY_BLP', 'translations' => array('field' => 'name', 'en_GB' => 'Belp', 'de_DE' => 'Belp'))), 'ALLER' => array(array('name' => 'CTY_ALLER', 'translations' => array('field' => 'name', 'en_GB' => 'Allershausen', 'de_DE' => 'Allershausen'))), 'ALCH' => array(array('name' => 'CTY_ALCH', 'translations' => array('field' => 'name', 'en_GB' => 'Aichach', 'de_DE' => 'Aichach'))), 'BAYE' => array(array('name' => 'CTY_BAYE', 'translations' => array('field' => 'name', 'en_GB' => 'Altdorf', 'de_DE' => 'Altdorf'))));
     foreach ($contentArray as $id => $contents) {
         foreach ($contents as $content) {
             if ($code === $id) {
                 $city = new City();
                 $city->setName($content['name']);
                 $city->setCounty($this->getReference($code));
                 $city->setLatitude(floatVal(rand(1, 99) . '.' . rand(11111, 99999)));
                 $city->setLongitude(floatVal(rand(1, 99) . '.' . rand(11111, 99999)));
                 foreach ($enabledLocale as $locales) {
                     if (array_key_exists($locales, $content['translations'])) {
                         $city->addTranslation(new CityTranslations($locales, $content['translations']['field'], $content['translations'][$locales]));
                     } else {
                         $city->addTranslation(new CityTranslations($locales, $content['translations']['field'], $content['translations'][$locale]));
                     }
                 }
                 $manager->persist($city);
                 $manager->flush();
                 $this->addReference($content['name'], $city);
             }
         }
     }
 }
Example #16
0
 /**
  * Tries to evaluate a constant value expressed as a string.
  *
  * @param string $exp
  * @param bool   $valid [optional] Outputs `true` if the expression was successfully evaluated.
  * @return mixed
  */
 static function evalConstant($exp, &$valid = null)
 {
     $exp = trim($exp);
     if ($exp !== '') {
         $valid = true;
         if ($exp[0] == '"' || $exp[0] == "'") {
             return substr($exp, 1, -1);
         }
         if (is_numeric($exp)) {
             return ctype_digit($exp) ? intval($exp) : floatVal($exp);
         }
         if (defined($exp)) {
             return constant($exp);
         }
     }
     $valid = false;
     return null;
 }
 public static function set_custom_price($cartandbuggy)
 {
     global $woocommerce;
     $pid = 0;
     $amt = 0;
     $qty = 0;
     $vri = 0;
     if (isset($_POST)) {
         if (isset($_POST[self::ID . '_pid']) || !empty($_POST[self::ID . '_pid'])) {
             $pid = intval(filter_var($_POST[self::ID . '_pid'], FILTER_SANITIZE_STRING));
         }
         if (isset($_POST[self::ID . '_amt']) || !empty($_POST[self::ID . '_amt'])) {
             $amt = floatval(filter_var($_POST[self::ID . '_amt'], FILTER_SANITIZE_STRING));
         }
         if (isset($_POST[self::ID . '_qty']) || !empty($_POST[self::ID . '_qty'])) {
             $qty = floatval(filter_var($_POST[self::ID . '_qty'], FILTER_SANITIZE_STRING));
         }
         if (isset($_POST[self::ID . '_vri']) || !empty($_POST[self::ID . '_vri'])) {
             $vri = intval(filter_var($_POST[self::ID . '_vri'], FILTER_SANITIZE_STRING));
         }
         if (!isset($pid) || !isset($amt) || !isset($vri) || $amt < 0 || $vri < 0 || $pid < 1) {
             // DOOP ... SHIT HAPPENS!
         } else {
             $min_amt = get_post_meta($pid, self::ID . '_amount_min_price', true);
             $max_amt = get_post_meta($pid, self::ID . '_amount_max_price', true);
             if (isset($min_amt) && !empty($min_amt)) {
                 $min_amt = floatVal($min_amt);
                 if ($amt < 0) {
                     $amt = 0;
                 }
                 if ($amt < $min_amt) {
                     $amt = $min_amt;
                 }
             }
             if (isset($max_amt) && !empty($max_amt)) {
                 $max_amt = floatVal($max_amt);
                 if ($amt > $max_amt && $max_amt > 0) {
                     $amt = $max_amt;
                 }
             }
             $cart_item['pwyw_price'] = $amt;
             $cart_item['pwyw_quantity'] = $qty;
             $cart_item['pwyw_product_id'] = $pid;
             $cart_item['pwyw_variation_id'] = $vri;
             $price = $amt;
             $product_enabled = get_post_meta($pid, self::ID . '_enable_for_product', true);
             foreach ($cartandbuggy->cart_contents as $key => $value) {
                 if ($product_enabled != '1' && $product_enabled != 'yes') {
                     continue;
                 }
                 $named_price = $woocommerce->session->__get($key . '_named_price');
                 if ($named_price) {
                     $value['pwyw_price'] = $named_price;
                     $value['data']->price = $named_price;
                 }
             }
         }
     }
 }
Example #18
0
    $_SESSION['search']['s'] = trim($_REQUEST['s']);
}
if (isset($_REQUEST['as'])) {
    $_SESSION['search']['as'] = $_REQUEST['as'];
    $_SESSION['search']['af'] = $_REQUEST['af'];
    $_SESSION['search']['aj'] = $_REQUEST['aj'];
    $_SESSION['search']['ctype'] = $_REQUEST['ctype'];
    $_SESSION['search']['categories'] = $_REQUEST['categories'];
    $_SESSION['search']['hd'] = $_REQUEST['hd'] ? true : false;
    $_SESSION['search']['commfree'] = $_REQUEST['commfree'] ? true : false;
    $_SESSION['search']['unwatched'] = $_REQUEST['unwatched'] ? true : false;
    $_SESSION['search']['scheduled'] = $_REQUEST['scheduled'] ? true : false;
    $_SESSION['search']['generic'] = $_REQUEST['generic'] ? true : false;
    $_SESSION['search']['distinctTitle'] = $_REQUEST['distinctTitle'] ? true : false;
    $_SESSION['search']['stars_gt'] = floatVal($_REQUEST['stars_gt']);
    $_SESSION['search']['stars_lt'] = floatVal($_REQUEST['stars_lt']);
    $_SESSION['search']['airdate_start'] = trim($_REQUEST['airdate_start']);
    $_SESSION['search']['airdate_end'] = trim($_REQUEST['airdate_end']);
    $_SESSION['search']['starttime'] = trim($_REQUEST['starttime']);
    $_SESSION['search']['endtime'] = trim($_REQUEST['endtime']);
}
// Session defaults
if (!is_array($_SESSION['search']['ctype']) || empty($_SESSION['search']['ctype'])) {
    $_SESSION['search']['ctype'] = Program::category_types();
}
if (!is_array($_SESSION['search']['categories']) || empty($_SESSION['search']['categories'])) {
    $_SESSION['search']['categories'] = array();
}
if (!isset($_SESSION['search']['stars_gt']) || !isset($_SESSION['search']['stars_lt'])) {
    $_SESSION['search']['stars_gt'] = 0;
    $_SESSION['search']['stars_lt'] = 1;
Example #19
0
 /** Get row evolution for a multiple labels */
 private function getMultiRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $labels, $segment, $column, $language = false, $idGoal = false, $legendAppendMetric = true, $labelUseAbsoluteUrl = true)
 {
     $actualLabels = $logos = array();
     $metadata = $this->getRowEvolutionMetaData($idSite, $period, $date, $apiModule, $apiAction, $language, $idGoal);
     if (!isset($metadata['metrics'][$column])) {
         // invalid column => use the first one that's available
         $metrics = array_keys($metadata['metrics']);
         $column = reset($metrics);
     }
     // load the tables for each label
     $dataTablesPerLabel = array();
     $dataTableMetadata = false;
     foreach ($labels as $labelIndex => $label) {
         $dataTable = $this->loadRowEvolutionDataFromAPI($idSite, $period, $date, $apiModule, $apiAction, $label, $segment, $idGoal);
         $dataTablesPerLabel[$labelIndex] = $dataTable->getArray();
         if (!$dataTableMetadata) {
             $dataTableMetadata = $dataTable->metadata;
         }
         $urlFound = false;
         foreach ($dataTablesPerLabel[$labelIndex] as $table) {
             if ($table->getRowsCount() > 0) {
                 $firstRow = $table->getFirstRow();
                 // in case labels were replaced in the data table (e.g. for browsers report),
                 // display the label from the table, not the one passed as filter
                 $columnLabel = $firstRow->getColumn('label');
                 if (!empty($columnLabel)) {
                     $actualLabels[$labelIndex] = $columnLabel;
                 }
                 list($actualLabel, $urlFound) = $this->cleanUrlForLabel($firstRow, $apiModule, $apiAction, $labelUseAbsoluteUrl);
                 if ($actualLabel) {
                     $actualLabels[$labelIndex] = $actualLabel;
                 }
                 // Forward the logo path to display logos in multi rows comparison
                 $logos[$labelIndex] = $firstRow->getMetadata('logo');
                 break;
             }
         }
         if (!$urlFound) {
             $actualLabels[$labelIndex] = str_replace(Piwik_API_DataTableManipulator_LabelFilter::SEPARATOR_RECURSIVE_LABEL, ' - ', $label);
         }
     }
     // combine the tables
     $dataTableMulti = new Piwik_DataTable_Array();
     $dataTableMulti->setKeyName($dataTable->getKeyName());
     $dataTableMulti->metadata = $dataTableMetadata;
     foreach (array_keys(reset($dataTablesPerLabel)) as $dateLabel) {
         $newRow = new Piwik_DataTable_Row();
         foreach ($dataTablesPerLabel as $labelIndex => $tableArray) {
             $table = $tableArray[$dateLabel];
             if ($table->getRowsCount() == 0) {
                 $value = 0;
             } else {
                 $value = $table->getFirstRow()->getColumn($column);
                 $value = floatVal(str_replace(',', '.', $value));
                 if ($value == '') {
                     $value = 0;
                 }
             }
             // keep metric in the label so that unit (%, s, ...) can be guessed correctly
             $label = $column . '_' . $labelIndex;
             $newRow->addColumn($label, $value);
         }
         $newTable = new Piwik_DataTable();
         $newTable->addRow($newRow);
         $dataTableMulti->addTable($newTable, $dateLabel);
     }
     // the available metrics for the report are returned as metadata / columns
     $metadata['columns'] = $metadata['metrics'];
     // metadata / metrics should document the rows that are compared
     // this way, UI code can be reused
     $metadata['metrics'] = array();
     foreach ($actualLabels as $labelIndex => $label) {
         if ($legendAppendMetric) {
             $label .= ' (' . $metadata['columns'][$column] . ')';
         }
         $metricName = $column . '_' . $labelIndex;
         $metadata['metrics'][$metricName] = Piwik_DataTable_Filter_SafeDecodeLabel::safeDecodeLabel($label);
         if (!empty($logos[$labelIndex])) {
             $metadata['logos'][$metricName] = $logos[$labelIndex];
         }
     }
     $this->enhanceRowEvolutionMetaData($metadata, $dataTableMulti);
     return array('column' => $column, 'reportData' => $dataTableMulti, 'metadata' => $metadata);
 }
Example #20
0
 public static function DoSaveToDav($Params = array(), &$arFields, $oCurEvent = false)
 {
     $sectionId = $Params['sectionId'];
     $bExchange = $Params['bExchange'];
     $bCalDav = $Params['bCalDav'];
     if (isset($oCurEvent['DAV_XML_ID'])) {
         $arFields['DAV_XML_ID'] = $oCurEvent['DAV_XML_ID'];
     }
     if (isset($oCurEvent['DAV_EXCH_LABEL'])) {
         $arFields['DAV_EXCH_LABEL'] = $oCurEvent['DAV_EXCH_LABEL'];
     }
     if (isset($oCurEvent['CAL_DAV_LABEL'])) {
         $arFields['CAL_DAV_LABEL'] = $oCurEvent['CAL_DAV_LABEL'];
     }
     $oSect = CCalendarSect::GetById($sectionId);
     if ($oCurEvent) {
         if ($oCurEvent['SECT_ID'] != $sectionId) {
             $bCalDav = CCalendar::IsCalDAVEnabled() && $oCurEvent['CAL_TYPE'] == 'user' && strlen($oCurEvent['CAL_DAV_LABEL']) > 0;
             $bExchangeEnabled = CCalendar::IsExchangeEnabled() && $oCurEvent['CAL_TYPE'] == 'user';
             if ($bExchangeEnabled || $bCalDav) {
                 $res = CCalendar::DoDeleteToDav(array('bCalDav' => $bCalDav, 'bExchangeEnabled' => $bExchangeEnabled, 'sectionId' => $oCurEvent['SECT_ID']), $oCurEvent);
                 if ($res !== true) {
                     return CCalendar::ThrowError($res);
                 }
             }
         }
     }
     $fromTs = CCalendar::Timestamp($arFields['DT_FROM']);
     $toTs = CCalendar::Timestamp($arFields['DT_TO']);
     if (!isset($arFields['DT_FROM_TS'])) {
         $arFields['DT_FROM_TS'] = $fromTs;
     }
     if (!isset($arFields['DT_TO_TS'])) {
         $arFields['DT_TO_TS'] = $toTs;
     }
     $arDavFields = $arFields;
     CCalendarEvent::CheckFields($arDavFields);
     if ($arDavFields['RRULE'] != '') {
         $arDavFields['RRULE'] = $arFields['RRULE'];
     }
     $arDavFields['DETAIL_TEXT'] = $arDavFields['DESCRIPTION'];
     $arDavFields['DETAIL_TEXT_TYPE'] = 'text';
     $arDavFields['ACTIVE_FROM'] = $arDavFields['DT_FROM'];
     $arDavFields['ACTIVE_TO'] = $arDavFields['DT_TO'];
     $arDavFields['PROPERTY_LOCATION'] = $arDavFields['LOCATION']['NEW'];
     if ($arDavFields['PROPERTY_LOCATION'] !== '') {
         $arDavFields['PROPERTY_LOCATION'] = CCalendar::GetTextLocation($arDavFields['PROPERTY_LOCATION']);
     }
     $arDavFields['PROPERTY_IMPORTANCE'] = $arDavFields['IMPORTANCE'];
     $arDavFields['REMIND_SETTINGS'] = '';
     if ($arFields['REMIND'] && is_array($arFields['REMIND']) && is_array($arFields['REMIND'][0])) {
         $arDavFields['REMIND_SETTINGS'] = floatVal($arFields['REMIND'][0]['count']) . '_' . $arFields['REMIND'][0]['type'];
     }
     // RRULE
     $arDavFields['PROPERTY_PERIOD_TYPE'] = 'NONE';
     if (is_array($arFields['RRULE']) && isset($arFields['RRULE']['FREQ']) && in_array($arFields['RRULE']['FREQ'], array('HOURLY', 'DAILY', 'MONTHLY', 'YEARLY', 'WEEKLY'))) {
         $arDavFields['PROPERTY_PERIOD_TYPE'] = $arFields['RRULE']['FREQ'];
         // Interval
         $arDavFields['PROPERTY_PERIOD_COUNT'] = isset($arFields['RRULE']['INTERVAL']) && intVal($arFields['RRULE']['INTERVAL']) > 1 ? intVal($arFields['RRULE']['INTERVAL']) : 1;
         if ($arFields['RRULE']['FREQ'] == 'WEEKLY' && isset($arFields['RRULE']['BYDAY'])) {
             //PROPERTY_PERIOD_ADDITIONAL
             $BYDAYS = array();
             $days = array('SU' => 0, 'MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6);
             $bydays = explode(',', $arFields['RRULE']['BYDAY']);
             foreach ($bydays as $day) {
                 $BYDAYS[] = $days[$day];
             }
             $arDavFields['PROPERTY_PERIOD_ADDITIONAL'] = implode(',', $BYDAYS);
         }
         $h24 = 60 * 60 * 24;
         if ($fromTs == $toTs) {
             $arDavFields['PROPERTY_EVENT_LENGTH'] = $h24;
         } else {
             $arDavFields['PROPERTY_EVENT_LENGTH'] = intVal($toTs - $fromTs);
             if ($arDavFields['PROPERTY_EVENT_LENGTH'] % $h24 == 0) {
                 // We have dates without times
                 $arDavFields['PROPERTY_EVENT_LENGTH'] += $h24;
             }
         }
         // Until date
         if (isset($arFields['RRULE']['UNTIL'])) {
             $periodTs = $arFields['RRULE']['UNTIL'];
         } else {
             $periodTs = CCalendar::GetMaxTimestamp();
         }
         $arDavFields['ACTIVE_TO'] = CCalendar::Date($periodTs);
     }
     // **** Synchronize with CalDav ****
     if ($bCalDav && $oSect['CAL_DAV_CON'] > 0) {
         // New event or move existent event to DAV calendar
         if ($arFields['ID'] <= 0 || $oCurEvent && !$oCurEvent['CAL_DAV_LABEL']) {
             $DAVRes = CDavGroupdavClientCalendar::DoAddItem($oSect['CAL_DAV_CON'], $oSect['CAL_DAV_CAL'], $arDavFields);
         } else {
             // Edit existent event
             $DAVRes = CDavGroupdavClientCalendar::DoUpdateItem($oSect['CAL_DAV_CON'], $oSect['CAL_DAV_CAL'], $oCurEvent['DAV_XML_ID'], $oCurEvent['CAL_DAV_LABEL'], $arDavFields);
         }
         if (!is_array($DAVRes) || !array_key_exists("XML_ID", $DAVRes)) {
             return CCalendar::CollectCalDAVErros($DAVRes);
         }
         // // It's ok, we successfuly save event to caldav calendar - and save it to DB
         $arFields['DAV_XML_ID'] = $DAVRes['XML_ID'];
         $arFields['CAL_DAV_LABEL'] = $DAVRes['MODIFICATION_LABEL'];
     } elseif ($bExchange && $oSect['IS_EXCHANGE'] && strlen($oSect['DAV_EXCH_CAL']) > 0 && $oSect['DAV_EXCH_CAL'] !== 0) {
         $ownerId = $arFields['OWNER_ID'];
         // New event  or move existent event to Exchange calendar
         if ($arFields['ID'] <= 0 || $oCurEvent && !$oCurEvent['DAV_EXCH_LABEL']) {
             $exchRes = CDavExchangeCalendar::DoAddItem($ownerId, $oSect['DAV_EXCH_CAL'], $arDavFields);
         } else {
             $exchRes = CDavExchangeCalendar::DoUpdateItem($ownerId, $oCurEvent['DAV_XML_ID'], $oCurEvent['DAV_EXCH_LABEL'], $arDavFields);
         }
         if (!is_array($exchRes) || !array_key_exists("XML_ID", $exchRes)) {
             return CCalendar::CollectExchangeErrors($exchRes);
         }
         // It's ok, we successfuly save event to exchange calendar - and save it to DB
         $arFields['DAV_XML_ID'] = $exchRes['XML_ID'];
         $arFields['DAV_EXCH_LABEL'] = $exchRes['MODIFICATION_LABEL'];
     }
     return true;
 }
Example #21
0
 public static function ConvertEntity($ownerType, $ownerId, $sectionId, $iblockId, $createdBy)
 {
     $eventsCount = 0;
     $sectCount = 0;
     $bs = new CIBlockSection();
     $ent_id = "IBLOCK_" . $iblockId . "_SECTION";
     $result = array('eventsCount' => 0, 'sectCount' => 0);
     $bSetAccessFromCalendar = true;
     $Access = array('G2' => CCalendar::GetAccessTasksByName('calendar_section', 'calendar_denied'));
     // CONVERT ACCESS:
     if ($ownerType == 'user') {
         if (!CSocNetFeatures::IsActiveFeature(SONET_ENTITY_USER, $ownerId, "calendar")) {
             return $result;
         }
         // Read
         $read = CSocNetFeaturesPerms::GetOperationPerm(SONET_ENTITY_USER, $ownerId, "calendar", 'view');
         $taskId = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_view');
         if ($read == 'A') {
             // All users
             $Access['G2'] = $taskId;
         } elseif ($read == 'C') {
             // All autorized
             $Access['AU'] = $taskId;
         } elseif ($read == 'M' || $read == 'E') {
             // Friends
             $Access['SU' . $ownerId . '_F'] = $taskId;
         } elseif ($bSetAccessFromCalendar) {
             $bSetAccessFromCalendar = false;
         }
         // Write - will override read access
         $write = CSocNetFeaturesPerms::GetOperationPerm(SONET_ENTITY_USER, $ownerId, "calendar", 'write');
         $taskId = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_edit');
         if ($write == 'A') {
             // All users
             $Access['G2'] = $taskId;
         } elseif ($write == 'C') {
             // All autorized
             $Access['AU'] = $taskId;
         } elseif ($write == 'M' || $write == 'E') {
             // Friends
             $Access['SU' . $ownerId . '_F'] = $taskId;
         }
     } elseif ($ownerType == 'group') {
         if (!CSocNetFeatures::IsActiveFeature(SONET_ENTITY_GROUP, $ownerId, "calendar")) {
             return $result;
         }
         // Read
         $read = CSocNetFeaturesPerms::GetOperationPerm(SONET_ENTITY_GROUP, $ownerId, "calendar", 'view');
         $taskId = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_view');
         if ($read == 'A') {
             // Group owner
             $Access['SG' . $ownerId . '_A'] = $taskId;
         } elseif ($read == 'E') {
             // Group moderator
             $Access['SG' . $ownerId . '_E'] = $taskId;
         } elseif ($read == 'K') {
             // User
             $Access['SG' . $ownerId . '_K'] = $taskId;
         } elseif ($read == 'L') {
             // Authorized
             $Access['AU'] = $taskId;
         } elseif ($read == 'N') {
             // Authorized
             $Access['G2'] = $taskId;
         }
         // Write - will override read access
         $write = CSocNetFeaturesPerms::GetOperationPerm(SONET_ENTITY_GROUP, $ownerId, "calendar", 'write');
         $taskId = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_edit');
         if ($write == 'A') {
             // Group owner
             $Access['SG' . $ownerId . '_A'] = $taskId;
         } elseif ($write == 'E') {
             // Group moderator
             $Access['SG' . $ownerId . '_E'] = $taskId;
         } elseif ($write == 'K') {
             // User
             $Access['SG' . $ownerId . '_K'] = $taskId;
         } elseif ($write == 'L') {
             // Authorized
             $Access['AU'] = $taskId;
         } elseif ($write == 'N') {
             // Authorized
             $Access['G2'] = $taskId;
         }
     } else {
         $arGroupPerm = CIBlock::GetGroupPermissions($iblockId);
         $taskByLetter = array('D' => CCalendar::GetAccessTasksByName('calendar_section', 'calendar_denied'), 'R' => CCalendar::GetAccessTasksByName('calendar_section', 'calendar_view'), 'W' => CCalendar::GetAccessTasksByName('calendar_section', 'calendar_edit'), 'X' => CCalendar::GetAccessTasksByName('calendar_section', 'calendar_access'));
         foreach ($arGroupPerm as $groupId => $letter) {
             $Access['G' . $groupId] = $taskByLetter[$letter];
         }
     }
     // 1. Fetch sections
     $arUserSections = CEventCalendar::GetCalendarList(array($iblockId, $sectionId, 0, $ownerType));
     $calendarIndex = array();
     foreach ($arUserSections as $section) {
         $arUF = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields($ent_id, $section['ID']);
         if (isset($arUF["UF_CAL_CONVERTED"]) && strlen($arUF["UF_CAL_CONVERTED"]['VALUE']) > 0) {
             continue;
         }
         $SectionAccess = array();
         if ($bSetAccessFromCalendar && $ownerType == 'user') {
             if ($section['PRIVATE_STATUS'] == 'private') {
                 $deniedTask = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_denied');
                 $SectionAccess['G2'] = $deniedTask;
             } elseif ($section['PRIVATE_STATUS'] == 'time') {
                 $viewTimeTask = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_view_time');
                 $SectionAccess['G2'] = $viewTimeTask;
             } elseif ($section['PRIVATE_STATUS'] == 'title') {
                 $viewTitleTask = CCalendar::GetAccessTasksByName('calendar_section', 'calendar_view_title');
                 $SectionAccess['G2'] = $viewTitleTask;
             } else {
                 $SectionAccess = $Access;
                 // nested from common access settings from socnet
             }
         } else {
             $SectionAccess = $Access;
             // G2 => denied
         }
         $new_sect_id = CCalendarSect::Edit(array('arFields' => array("CAL_TYPE" => $ownerType, "NAME" => $section['NAME'], "OWNER_ID" => $ownerId, "CREATED_BY" => $createdBy, "DESCRIPTION" => $section['DESCRIPTION'], "COLOR" => $section["COLOR"], "ACCESS" => $SectionAccess)));
         // Set converted property
         $bs->Update($section['ID'], array('UF_CAL_CONVERTED' => 1));
         $calendarIndex[$section['ID']] = $new_sect_id;
         $sectCount++;
     }
     // 2. Create events
     $arEvents = CEventCalendar::GetCalendarEventsList(array($iblockId, $sectionId, 0), array());
     foreach ($arEvents as $event) {
         if (!isset($calendarIndex[$event['IBLOCK_SECTION_ID']]) || $event['PROPERTY_PARENT'] > 0) {
             continue;
         }
         $arFields = array("CAL_TYPE" => $ownerType, "OWNER_ID" => $ownerId, "CREATED_BY" => $event["CREATED_BY"], "DT_FROM" => $event['ACTIVE_FROM'], "DT_TO" => $event['ACTIVE_TO'], 'NAME' => htmlspecialcharsback($event['NAME']), 'DESCRIPTION' => CCalendar::ParseHTMLToBB(htmlspecialcharsback($event['DETAIL_TEXT'])), 'SECTIONS' => array($calendarIndex[$event['IBLOCK_SECTION_ID']]), 'ACCESSIBILITY' => $event['PROPERTY_ACCESSIBILITY'], 'IMPORTANCE' => $event['PROPERTY_IMPORTANCE'], 'PRIVATE_EVENT' => $event['PROPERTY_PRIVATE'] && $event['PROPERTY_PRIVATE'] == 'true' ? '1' : '', 'RRULE' => array(), 'LOCATION' => array('NEW' => $event['PROPERTY_LOCATION'], 'RE_RESERVE' => 'N'), "REMIND" => array(), "IS_MEETING" => $event['PROPERTY_IS_MEETING'] == 'Y');
         if (!empty($event['PROPERTY_REMIND_SETTINGS'])) {
             $ar = explode("_", $event["PROPERTY_REMIND_SETTINGS"]);
             if (count($ar) == 2) {
                 $arFields["REMIND"][] = array('type' => $ar[1], 'count' => floatVal($ar[0]));
             }
         }
         if (isset($event["PROPERTY_PERIOD_TYPE"]) && in_array($event["PROPERTY_PERIOD_TYPE"], array("DAILY", "WEEKLY", "MONTHLY", "YEARLY"))) {
             $arFields['RRULE']['FREQ'] = $event["PROPERTY_PERIOD_TYPE"];
             $arFields['RRULE']['INTERVAL'] = $event["PROPERTY_PERIOD_COUNT"];
             if (!empty($event['PROPERTY_EVENT_LENGTH'])) {
                 $arFields['DT_LENGTH'] = intval($event['PROPERTY_EVENT_LENGTH']);
             }
             if (!$arFields['DT_LENGTH']) {
                 $arFields['DT_LENGTH'] = 86400;
             }
             if ($arFields['RRULE']['FREQ'] == "WEEKLY" && !empty($event['PROPERTY_PERIOD_ADDITIONAL'])) {
                 $arFields['RRULE']['BYDAY'] = array();
                 $bydays = explode(',', $event['PROPERTY_PERIOD_ADDITIONAL']);
                 foreach ($bydays as $day) {
                     $day = CCalendar::WeekDayByInd($day);
                     if ($day !== false) {
                         $arFields['RRULE']['BYDAY'][] = $day;
                     }
                 }
                 $arFields['RRULE']['BYDAY'] = implode(',', $arFields['RRULE']['BYDAY']);
             }
             $arFields['RRULE']['UNTIL'] = $event['ACTIVE_TO'];
         }
         if ($arFields['IS_MEETING']) {
             if ($event['PROPERTY_PARENT'] > 0) {
                 continue;
             }
             $host = intVal($event['CREATED_BY']);
             $arFields['ATTENDEES'] = array();
             if ($event['PROPERTY_HOST_IS_ABSENT'] == 'N') {
                 $arFields['ATTENDEES'][] = $host;
             }
             $arGuests = CECEvent::GetGuests(self::$userIblockId, $event['ID']);
             $attendeesStatuses = array();
             foreach ($arGuests as $userId => $ev) {
                 $attendeesStatuses[$userId] = $ev['PROPERTY_VALUES']['CONFIRMED'];
                 $arFields['ATTENDEES'][] = $userId;
             }
             $arFields['MEETING_HOST'] = $host;
             $arFields['MEETING'] = array('HOST_NAME' => CCalendar::GetUserName($host), 'TEXT' => is_array($event['PROPERTY_MEETING_TEXT']) && is_string($event['PROPERTY_MEETING_TEXT']['TEXT']) ? trim($event['PROPERTY_MEETING_TEXT']['TEXT']) : '', 'OPEN' => false, 'NOTIFY' => false, 'REINVITE' => false);
         }
         $new_event_id = CCalendar::SaveEvent(array('arFields' => $arFields, 'bAffectToDav' => false, 'attendeesStatuses' => $attendeesStatuses, 'bSendInvitations' => false));
         $eventsCount++;
     }
     // 3. Set userfield
     $bs->Update($sectionId, array('UF_CAL_CONVERTED' => 1));
     return array('eventsCount' => $eventsCount, 'sectCount' => $sectCount);
 }
Example #22
0
 private function initJsonStats()
 {
     $json = array('id' => $this->id, 'name' => $this->getField('name', true), 'quality' => ITEM_QUALITY_HEIRLOOM - $this->curTpl['quality'], 'icon' => $this->curTpl['iconString'], 'classs' => $this->curTpl['class'], 'subclass' => $this->curTpl['subClass'], 'subsubclass' => $this->curTpl['subSubClass'], 'heroic' => ($this->curTpl['flags'] & 0x8) >> 3, 'side' => $this->curTpl['flagsExtra'] & 0x3 ? 3 - ($this->curTpl['flagsExtra'] & 0x3) : Util::sideByRaceMask($this->curTpl['requiredRace']), 'slot' => $this->curTpl['slot'], 'slotbak' => $this->curTpl['slotBak'], 'level' => $this->curTpl['itemLevel'], 'reqlevel' => $this->curTpl['requiredLevel'], 'displayid' => $this->curTpl['displayId'], 'holres' => $this->curTpl['resHoly'], 'firres' => $this->curTpl['resFire'], 'natres' => $this->curTpl['resNature'], 'frores' => $this->curTpl['resFrost'], 'shares' => $this->curTpl['resShadow'], 'arcres' => $this->curTpl['resArcane'], 'armorbonus' => $this->curTpl['armorDamageModifier'], 'armor' => $this->curTpl['armor'], 'dura' => $this->curTpl['durability'], 'itemset' => $this->curTpl['itemset'], 'socket1' => $this->curTpl['socketColor1'], 'socket2' => $this->curTpl['socketColor2'], 'socket3' => $this->curTpl['socketColor3'], 'nsockets' => ($this->curTpl['socketColor1'] > 0 ? 1 : 0) + ($this->curTpl['socketColor2'] > 0 ? 1 : 0) + ($this->curTpl['socketColor3'] > 0 ? 1 : 0), 'socketbonus' => $this->curTpl['socketBonus'], 'scadist' => $this->curTpl['scalingStatDistribution'], 'scaflags' => $this->curTpl['scalingStatValue']);
     if ($this->curTpl['class'] == ITEM_CLASS_WEAPON || $this->curTpl['class'] == ITEM_CLASS_AMMUNITION) {
         $json['dmgtype1'] = $this->curTpl['dmgType1'];
         $json['dmgmin1'] = $this->curTpl['dmgMin1'] + $this->curTpl['dmgMin2'];
         $json['dmgmax1'] = $this->curTpl['dmgMax1'] + $this->curTpl['dmgMax2'];
         $json['speed'] = number_format($this->curTpl['delay'] / 1000, 2);
         $json['dps'] = !floatVal($json['speed']) ? 0 : number_format(($json['dmgmin1'] + $json['dmgmax1']) / (2 * $json['speed']), 1);
         if (in_array($json['subclass'], [2, 3, 18, 19])) {
             $json['rgddmgmin'] = $json['dmgmin1'];
             $json['rgddmgmax'] = $json['dmgmax1'];
             $json['rgdspeed'] = $json['speed'];
             $json['rgddps'] = $json['dps'];
         } else {
             if ($json['classs'] != ITEM_CLASS_AMMUNITION) {
                 $json['mledmgmin'] = $json['dmgmin1'];
                 $json['mledmgmax'] = $json['dmgmax1'];
                 $json['mlespeed'] = $json['speed'];
                 $json['mledps'] = $json['dps'];
             }
         }
         if ($fap = $this->getFeralAP()) {
             $json['feratkpwr'] = $fap;
         }
     }
     if ($this->curTpl['armorDamageModifier'] > 0) {
         $json['armor'] += $this->curTpl['armorDamageModifier'];
     }
     // clear zero-values afterwards
     foreach ($json as $k => $v) {
         if (!$v && !in_array($k, ['classs', 'subclass', 'quality', 'side'])) {
             unset($json[$k]);
         }
     }
     Util::checkNumeric($json);
     $this->json[$json['id']] = $json;
 }
Example #23
0
 /**
  * color value to convert
  *
  * @access protected
  * @param  string $c
  * @return float $c 0.->1.
  */
 protected function _convertSubColor($c)
 {
     if (substr($c, -1) == '%') {
         $c = floatVal(substr($c, 0, -1)) / 100.0;
     } else {
         $c = floatVal($c);
         if ($c > 1) {
             $c = $c / 255.0;
         }
     }
     return $c;
 }
Example #24
0
 private function jsencode($obj, $json = false)
 {
     switch (gettype($obj)) {
         case 'array':
         case 'object':
             $code = array();
             // is it anything other than a simple linear array
             if (array_keys($obj) !== range(0, count($obj) - 1)) {
                 foreach ($obj as $key => $val) {
                     $code[] = $json ? '"' . $key . '":' . $this->jsencode($val) : $key . ':' . $this->jsencode($val);
                 }
                 $code = '{' . implode(',', $code) . '}';
             } else {
                 foreach ($obj as $val) {
                     $code[] = $this->jsencode($val);
                 }
                 $code = '[' . implode(',', $code) . ']';
             }
             return $code;
             break;
         case 'boolean':
             return $obj ? 'true' : 'false';
             break;
         case 'integer':
         case 'double':
             return floatVal($obj);
             break;
         case 'NULL':
         case 'resource':
         case 'unknown':
             return 'null';
             break;
         default:
             return '"' . addslashes($obj) . '"';
     }
 }
Example #25
0
if (COption::GetOptionString("blog", "allow_video", "Y") == "Y" && $arParams["ALLOW_VIDEO"] == "Y") {
    $arResult["allowVideo"] = true;
}
$user_id = $USER->GetID();
$arResult["canModerate"] = false;
$blogModulePermissions = $GLOBALS["APPLICATION"]->GetGroupRight("blog");
if ($arParams["NO_URL_IN_COMMENTS"] == "L") {
    $arResult["NoCommentUrl"] = true;
    $arResult["NoCommentReason"] = GetMessage("B_B_PC_MES_NOCOMMENTREASON_L");
}
if (!$USER->IsAuthorized() && $arParams["NO_URL_IN_COMMENTS"] == "A") {
    $arResult["NoCommentUrl"] = true;
    $arResult["NoCommentReason"] = GetMessage("B_B_PC_MES_NOCOMMENTREASON_A");
}
if (is_numeric($arParams["NO_URL_IN_COMMENTS_AUTHORITY"])) {
    $arParams["NO_URL_IN_COMMENTS_AUTHORITY"] = floatVal($arParams["NO_URL_IN_COMMENTS_AUTHORITY"]);
    $arParams["NO_URL_IN_COMMENTS_AUTHORITY_CHECK"] = "Y";
    if ($USER->IsAuthorized()) {
        $authorityRatingId = CRatings::GetAuthorityRating();
        $arRatingResult = CRatings::GetRatingResult($authorityRatingId, $user_id);
        if ($arRatingResult["CURRENT_VALUE"] < $arParams["NO_URL_IN_COMMENTS_AUTHORITY"]) {
            $arResult["NoCommentUrl"] = true;
            $arResult["NoCommentReason"] = GetMessage("B_B_PC_MES_NOCOMMENTREASON_R");
        }
    }
}
if (empty($arBlog)) {
    $arBlog = CBlog::GetByUrl($arParams["BLOG_URL"], $arParams["GROUP_ID"]);
    $arBlog = CBlogTools::htmlspecialcharsExArray($arBlog);
}
$arGroup = CBlogGroup::GetByID($arBlog["GROUP_ID"]);
Example #26
0
 public static function GetDouble($param, $default = false, $source = null)
 {
     $source = $source ?: $_GET;
     return isset($source[$param]) && is_numeric($source[$param]) ? floatVal($source[$param]) : $default;
 }
 /** Get row evolution for a multiple labels */
 private function getMultiRowEvolution(DataTable\Map $dataTable, $metadata, $apiModule, $apiAction, $labels, $column, $legendAppendMetric = true, $labelUseAbsoluteUrl = true)
 {
     if (!isset($metadata['metrics'][$column])) {
         // invalid column => use the first one that's available
         $metrics = array_keys($metadata['metrics']);
         $column = reset($metrics);
     }
     // get the processed label and logo (if any) for every requested label
     $actualLabels = $logos = array();
     foreach ($labels as $labelIdx => $label) {
         foreach ($dataTable->getDataTables() as $table) {
             $labelRow = $this->getRowEvolutionRowFromLabelIdx($table, $labelIdx);
             if ($labelRow) {
                 $actualLabels[$labelIdx] = $this->getRowUrlForEvolutionLabel($labelRow, $apiModule, $apiAction, $labelUseAbsoluteUrl);
                 $logos[$labelIdx] = $labelRow->getMetadata('logo');
                 if (!empty($actualLabels[$labelIdx])) {
                     break;
                 }
             }
         }
         if (empty($actualLabels[$labelIdx])) {
             $actualLabels[$labelIdx] = $this->cleanOriginalLabel($label);
         }
     }
     // convert rows to be array($column.'_'.$labelIdx => $value) as opposed to
     // array('label' => $label, 'column' => $value).
     $dataTableMulti = $dataTable->getEmptyClone();
     foreach ($dataTable->getDataTables() as $tableLabel => $table) {
         $newRow = new Row();
         foreach ($labels as $labelIdx => $label) {
             $row = $this->getRowEvolutionRowFromLabelIdx($table, $labelIdx);
             $value = 0;
             if ($row) {
                 $value = $row->getColumn($column);
                 $value = floatVal(str_replace(',', '.', $value));
             }
             if ($value == '') {
                 $value = 0;
             }
             $newLabel = $column . '_' . (int) $labelIdx;
             $newRow->addColumn($newLabel, $value);
         }
         $newTable = $table->getEmptyClone();
         if (!empty($labels)) {
             // only add a row if the row has data (no labels === no data)
             $newTable->addRow($newRow);
         }
         $dataTableMulti->addTable($newTable, $tableLabel);
     }
     // the available metrics for the report are returned as metadata / columns
     $metadata['columns'] = $metadata['metrics'];
     // metadata / metrics should document the rows that are compared
     // this way, UI code can be reused
     $metadata['metrics'] = array();
     foreach ($actualLabels as $labelIndex => $label) {
         if ($legendAppendMetric) {
             $label .= ' (' . $metadata['columns'][$column] . ')';
         }
         $metricName = $column . '_' . $labelIndex;
         $metadata['metrics'][$metricName] = SafeDecodeLabel::decodeLabelSafe($label);
         if (!empty($logos[$labelIndex])) {
             $metadata['logos'][$metricName] = $logos[$labelIndex];
         }
     }
     $this->enhanceRowEvolutionMetaData($metadata, $dataTableMulti);
     return array('column' => $column, 'reportData' => $dataTableMulti, 'metadata' => $metadata);
 }
Example #28
0
function makecontact_execute($action, $slot)
{
    global $_POST;
    global $_GET;
    global $_CONFIG;
    require_once "config/db.php";
    global $conn;
    global $_local_error;
    $_local_error = "";
    global $_local_reloadform;
    $_local_reloadform = "";
    global $render_current_slot;
    global $current_slots;
    //mark slot on execution stack
    $render_current_slot++;
    $current_slots[$render_current_slot] = $slot;
    if (getUserConfig("pageprotection") == "yes") {
        if (isset($_POST['fprotection']) && $_POST['fprotection'] != "") {
            if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
                if (intval(session_getvalue("protection_page")) != intval($_POST['fprotection'])) {
                    $_local_error = getLT("protectionerror");
                }
            } else {
                if (intval(session_getvalue("protection_page")) != intval($_POST['fprotection']) + 1) {
                    $_local_error = getLT("protectionerror");
                }
            }
        }
    }
    //set default filter
    $control_filter = "";
    $control_name = "makecontact";
    $control_table = "projectissues";
    $control_id = "id";
    //check for rights
    if (getUserConfig('dinsec_makecontact_cando', $action) == 'no') {
        $_local_error = getLT('nopermissions');
    }
    if (getUserConfig('dinsec_makecontact_canpost', $action) == 'no') {
        $_local_error = getLT('nopermissions');
    }
    if (session_getvalue("blockaccess_makecontact") == "yes") {
        $_local_error = getLT('nopermissions');
    }
    if (session_getvalue("blockaccess_projectissues") == "yes") {
        $_local_error = getLT('nopermissions');
    }
    if ($_local_error == "") {
        switch ($action) {
            case 'add':
                if (isset($_POST['cancel_button']) && $_POST['cancel_button'] == getLT('cancel')) {
                    $_local_error = 'usercanceled';
                    setSlotView($slot, "add");
                    break;
                }
                if ($_local_error == '') {
                    if (!isset($_POST['iname']) || $_POST['iname'] == '' || strip_tags($_POST['iname']) == '') {
                        $_local_error .= getLT('iname') . ' ' . getLT('shouldbefilled');
                    }
                }
                if ($_local_error == '') {
                    if (!isset($_POST['iemail']) || $_POST['iemail'] == '' || strip_tags($_POST['iemail']) == '') {
                        $_local_error .= getLT('iemail') . ' ' . getLT('shouldbefilled');
                    }
                }
                if ($_local_error == '') {
                    if (!isset($_POST['icontactname']) || $_POST['icontactname'] == '' || strip_tags($_POST['icontactname']) == '') {
                        $_local_error .= getLT('icontactname') . ' ' . getLT('shouldbefilled');
                    }
                }
                if ($_local_error == '') {
                    if (!isset($_POST['useraddress'])) {
                        $_local_error .= getLT('javascript?');
                    } else {
                        $ab_def = strtok($_POST['useraddress'], "-");
                        $ab_test = $ab_def . '-' . number_format(floatVal($ab_def . '.12') * 0.34, 4, '.', '');
                        if ($ab_test !== $_POST['useraddress']) {
                            $_local_error .= getLT('antiboterror?');
                        }
                    }
                }
                if ($_local_error == "") {
                    $conn->addnew($control_table);
                    $conn->setvalue('iname', correctPostValue($_POST['iname']));
                    $conn->setvalue('iemail', correctPostValue($_POST['iemail']));
                    $conn->setvalue('icontactname', correctPostValue($_POST['icontactname']));
                    $html = correctPostValue($_POST['idesc']);
                    $html = str_ireplace("<script", "[script", $html);
                    $html = str_ireplace("<link", "[link", $html);
                    $html = str_ireplace("<style", "[style", $html);
                    $conn->setvalue('idesc', $html);
                    $conn->setvalue('projectid', $_CONFIG['projectid']);
                    $conn->setvalue('idate', date("Y-m-d H:i:s"));
                    $id = $conn->update();
                    if ($id != "") {
                        session_addvalue($slot . '_info', getLT('wblank'));
                        session_setvalue($slot . "_viewid", $id);
                        setSlotView($slot, "add");
                    } else {
                        $_local_error = getLT('unableadd');
                        break;
                    }
                }
            case 'sendemail':
                if (isset($_POST['cancel_button']) && $_POST['cancel_button'] == getLT('cancel')) {
                    $_local_error = 'usercanceled';
                    break;
                }
                if ($_local_error == "") {
                    ob_start();
                    require_once "config/htmlreport.php";
                    require_once "config/templates.php";
                    require_once "config/mail.php";
                    global $_templates;
                    require_once "config/utils.php";
                    $_control_replace_sql = "parseAndReplaceAll";
                    $pdf = new HtmlReport("");
                    $emailbody = ob_get_contents();
                    ob_end_clean();
                    $emailbody = html_entity_decode($emailbody);
                    $emailsubject = getLT('emailcontact');
                    global $mails_sql_conn;
                    $mails_sql_conn = create_db_connection();
                    $mails_sql_conn->openselect($_control_replace_sql("select pemails as email from projects where id=0[config.projectid]"));
                    $noemail = false;
                    if ($mails_sql_conn->eof()) {
                        $noemail = true;
                    }
                    while (!$mails_sql_conn->eof()) {
                        $mailman = createMailObject();
                        $mailman->IsHTML(true);
                        $emailto = $mails_sql_conn->getvalue("email");
                        $emailreply = "";
                        $emailbcc = "";
                        $emailcc = "";
                        $emailfrom = "";
                        $emailbody = getFileContent(getFilePathFor('html', 'makecontact'));
                        require_once "config/utils.php";
                        $emailbody = parseAndReplaceAll($emailbody);
                        $emailreply = correctPostValue($_POST["iemail"]);
                        $mailman->Body = $emailbody;
                        $mailman->Subject = $emailsubject;
                        $mailman->ClearAddresses();
                        $mailman->AddAddress($emailto);
                        if ($emailbcc != "") {
                            $mailman->AddBCC($emailbcc);
                        }
                        if ($emailcc != "") {
                            $mailman->AddCC($emailcc);
                        }
                        if ($emailfrom != "") {
                            $mailman->FromName = "";
                            $mailman->From = $emailfrom;
                        }
                        if ($emailreply != '') {
                            $mailman->AddReplyTo($emailreply);
                        }
                        $mailman->send();
                        $mails_sql_conn->movenext();
                    }
                    $mails_sql_conn->close();
                    if ($noemail) {
                        session_addvalue($slot . '_error', getLT('noemailfound'));
                    } else {
                        session_addvalue($slot . '_info', getLT('yourmessageissent'));
                    }
                }
                break;
            default:
                //$_local_error="slot:".$slot." unknown post action: ".$action;
                setSlotView($slot, "");
                break;
        }
    }
    if (isset($_POST['cancel_button']) && $_POST['cancel_button'] == getLT('cancel')) {
        //if($_local_error!="") session_addvalue($slot.'_error',getLT($_local_error));
        $_local_error = '';
    } else {
        if ($_local_reloadform != "" || $_local_error != "" || $action == "justreloadform") {
            //save post for later use
            foreach ($_POST as $key => $val) {
                if (is_array($val)) {
                    session_setvalue('savedpost_makecontact_' . $key, correctPostValue(implode(",", str_replace(',', ' ', $_POST[$key]))));
                } else {
                    session_setvalue('savedpost_makecontact_' . $key, correctPostValue($val));
                }
            }
            if ($_local_error != "") {
                session_addvalue($slot . '_error', $_local_error);
            }
        }
    }
    $render_current_slot--;
    return $_local_error;
}
Example #29
0
 function tracking_details_response()
 {
     global $error_handler;
     $search = array(chr(0), chr(1), chr(2), chr(7), 'Add-1', 'Add-2', 'ConAdd-1', 'ConAdd-2', 'Rec-Status', 'Sh-BOL', 'Appt-Rqd', chr(26));
     $replace = array('', '', '', '', 'Add1', 'Add2', 'ConAdd1', 'ConAdd2', 'RecStatus', 'ShBOL', 'ApptRqd', '');
     $xml = new SimpleXMLElement(str_replace($search, $replace, $this->response));
     $return = array();
     if ($xml->TRACKING_DETAILS->ERROR->count()) {
         return false;
     }
     // JR: do not delete. This fixes the broken XML that Degama sends us
     // and formats it so that the shows the right calculations and numbers.
     $FirstRate = new SimpleXMLElement($xml->TRACKING_DETAILS->Order->RateDetails->asXML());
     $newRatesXml = new SimpleXMLElement("<rates></rates>");
     $newRatesXml->addChild('Rate');
     $newRatesXml->Rate->addChild('Line', 0);
     $newRatesXml->Rate->addChild('Code', (string) $FirstRate->ComCode);
     $newRatesXml->Rate->addChild('Descr1', htmlspecialchars($FirstRate->ComDescr->asXML()));
     $newRatesXml->Rate->addChild('Quant', floatval($FirstRate->Quant) == '0' ? '-' : floatval($FirstRate->Quant));
     $newRatesXml->Rate->addChild('Weight', floatval($FirstRate->Weight) == '0' ? floatval($xml->TRACKING_DETAILS->Order->Weight) : floatval($FirstRate->Weight));
     $newRatesXml->Rate->addChild('Rate', number_format(floatval($FirstRate->Rate), 2, '.', ''));
     $newRatesXml->Rate->addChild('Uom', (string) $FirstRate->Uom);
     $newRatesXml->Rate->addChild('Tot', number_format(floatval($FirstRate->Tot), 2, '.', ''));
     $newRatesXml->Rate->addChild('Surcharge', number_format(floatval($FirstRate->Surcharge), 2, '.', ''));
     $newTotalXml = floatval($FirstRate->Tot);
     $newSubtotal = floatval($FirstRate->Tot);
     $StatusLog = new SimpleXMLElement($xml->TRACKING_DETAILS->Order->StatusLog->asXML());
     unset($xml->TRACKING_DETAILS->Order->StatusLog);
     $newStatusLog = $xml->TRACKING_DETAILS->Order->addChild('StatusLog');
     foreach ($StatusLog->Status as $status) {
         $ns = $newStatusLog->addChild('Status');
         foreach ($status->children() as $child) {
             if ($child->getName() == 'Tm') {
                 $ns->addChild($child->getName(), $this->format_time_response($child));
             } else {
                 $ns->addChild($child->getName(), htmlspecialchars($child));
             }
         }
     }
     foreach ($xml->TRACKING_DETAILS->Order->RateDetails->Rates->Rate as $rate) {
         $nr = $newRatesXml->addChild('Rate');
         $newTotalXml = $newTotalXml + floatval($rate->Tot);
         $newSubtotal = $newSubtotal + floatval($rate->Tot);
         foreach ($rate->children() as $child) {
             if ($child->getName() == 'Rate' || $child->getName() == 'Tot') {
                 $nr->addChild($child->getName(), number_format(floatval($child), 2, '.', ''));
             } elseif ($child->getName() == 'Quant' && $child == '0') {
                 $nr->addChild($child->getName(), '-');
             } else {
                 $nr->addChild($child->getName(), $child);
             }
         }
         if ($rate->Code == '' && (empty($rate->Tot) || floatval($rate->Tot) == 0)) {
             $nr->Rate = '';
             $nr->Tot = '';
             $nr->Quant = '';
             $nr->Weight = '';
         }
     }
     unset($xml->TRACKING_DETAILS->Order->RateDetails->Rates);
     $rates = $xml->TRACKING_DETAILS->Order->RateDetails->addChild('Rates');
     foreach ($newRatesXml->Rate as $rate) {
         $nr = $rates->addChild('Rate', $rate);
         foreach ($rate->children() as $child) {
             $nr->addChild($child->getName(), $child);
         }
     }
     $newTotalXml = $newTotalXml + floatval($xml->TRACKING_DETAILS->Order->Gstamt) + floatval($FirstRate->Surcharge);
     $xml->TRACKING_DETAILS->Order->RateDetails->Surcharge = number_format(floatval($xml->TRACKING_DETAILS->Order->RateDetails->Surcharge), 2, '.', '');
     $xml->TRACKING_DETAILS->Order->Tot = number_format($newTotalXml, 2, '.', '');
     $xml->TRACKING_DETAILS->Order->RateDetails->Tot = number_format($newTotalXml, 2, '.', '');
     $xml->TRACKING_DETAILS->Order->RateDetails->Subtotal = number_format($newSubtotal + floatVal($xml->TRACKING_DETAILS->Order->RateDetails->Surcharge), 2, '.', '');
     $xml->TRACKING_DETAILS->Order->RateDetails->Gstamt = number_format(floatval($xml->TRACKING_DETAILS->Order->RateDetails->Gstamt), 2, '.', '');
     $details = $xml->TRACKING_DETAILS->Order->asXML();
     $return = $this->to_json_array($details);
     return $return;
 }
 public function cell_donor_amount($sCell, $iPostID)
 {
     // cell_{post type}_{column key}
     $donation_list = get_post_meta($iPostID, '_dgx_donate_donor_donations', true);
     $amount = floatval(0.0);
     $donation_id_array = explode(',', $donation_list);
     $donation_id_array = array_values(array_filter($donation_id_array));
     // remove empty elements from the array
     while ($donation_id = current($donation_id_array)) {
         $new_amount = floatVal(get_post_meta($donation_id, '_dgx_donate_amount', true));
         $amount += $new_amount;
         next($donation_id_array);
     }
     $currency_code = dgx_donate_get_donation_currency_code($donation_id);
     $formatted_amount = dgx_donate_get_escaped_formatted_amount($amount, 2, $currency_code);
     return esc_attr($formatted_amount);
 }