public function transform(Loan $item)
 {
     //return $item->toArray();
     $hasAttachments = false;
     $dtToday = Carbon::now();
     $appDate = Carbon::createFromFormat('Y-m-d', $item->app_date);
     $defaultDueDate = Carbon::createFromFormat('Y-m-d', $item->default_due_date);
     $dueDate = Carbon::createFromFormat('Y-m-d', $item->due_date);
     $diff = $dueDate->diffInDays($appDate);
     $staleDiff = $appDate->diffInDays($dtToday);
     $pastDueDiff = $dueDate->diffInDays($dtToday);
     //dd($staleDiff);
     if ($item->loan_type_id == 1 || $item->loan_type_id == 2 || $item->loan_type_id == 3) {
         $cropLoan = true;
     } else {
         $cropLoan = false;
     }
     //is_stale
     if (!$item->decision_date) {
         $decision = null;
         if ($staleDiff > 3 && $item->status_id == 1) {
             $isStale = true;
         } else {
             $isStale = false;
         }
         // end if
     } else {
         $isStale = false;
         $staleDiff = 0;
     }
     // end if
     //has_attachments
     if (count($item->attachments) > 0) {
         $hasAttachments = true;
     }
     //warning Past Due
     if ($pastDueDiff < 10) {
         $pastDue = 2;
     } elseif ($pastDueDiff < 30) {
         $pastDue = 1;
     } else {
         $pastDue = 0;
     }
     if ($item->season == 'F') {
         $fullSeason = 'Fall';
     } else {
         $fullSeason = 'Spring';
     }
     // Calculations for fins object
     $total_acres = getTotalAcres($item->id);
     $commitArm = getTotalPartyCommit('arm', $item->id);
     $commitDist = getTotalPartyCommit('dist', $item->id);
     $commitOther = getTotalPartyCommit('other', $item->id);
     $feeProc = $item->termmods->last()->fee_processing_arm;
     $feeSvc = $item->termmods->last()->fee_service_arm;
     $intPercentArm = $item->termmods->last()->int_percent_arm;
     $intPercentDist = $item->termmods->last()->int_percent_dist;
     $estDays = $item->termmods->last()->est_days;
     return ['fins' => ['discounts' => ['percent_crop' => (double) $item->discounts['disc_percent_crop'], 'percent_fsa' => (double) $item->discounts['disc_percent_fsa'], 'percent_ins' => (double) $item->discounts['disc_percent_ins'], 'percent_insoyield' => (double) $item->discounts['disc_percent_insoyield'], 'percent_nonrp' => (double) $item->discounts['disc_percent_nonrp'], 'percent_rphpe' => (double) $item->discounts['disc_percent_rphpe'], 'percent_suppins' => (double) $item->discounts['disc_percent_suppins'], 'percent_prod' => (double) $item->discounts['disc_percent_prod'], 'percent_equipment' => (double) $item->discounts['disc_percent_equipment'], 'percent_realestate' => (double) $item->discounts['disc_percent_realestate'], 'percent_other' => (double) $item->discounts['disc_percent_other']], 'amount_requested' => $item->applicants->fins['amount_requested'] ? $item->applicants->fins['amount_requested'] : $commitArm, 'arm_crop_commit' => getPartyCropsCommit($item->id, 'arm'), 'arm_cat_expense' => getPartyCatTotalExpenses($item->id, 'arm'), 'balance_spent' => (double) getArmTotalSpent($item->id), 'balance_total' => (double) getArmTotalBudget($item->id), 'balance_remaining' => (double) getArmTotalRemaining($item->id), 'cash_flow' => calcCashFlow($item), 'commit_arm' => $commitArm > 0 ? $commitArm : $item->financials['amount_requested'], 'commit_dist' => $commitDist, 'commit_other' => $commitOther, 'commit_total' => (double) $commitArm + (double) $commitDist, 'counties_in_loan' => getCountiesInLoan($item->id), 'crop_acres' => getAllCropAcres($item->id), 'cropids_in_loan' => getCropIDsInLoan($item->id), 'crops_in_loan' => getCropsInLoan($item->id), 'default_aph' => processDefaultAPH($item), 'dist_cat_expense' => getPartyCatTotalExpenses($item->id, 'dist'), 'dist_buyDown' => (bool) $item->financials['dist_buyDown'], 'dist_crop_commit' => getPartyCropsCommit($item->id, 'dist'), 'existing_crops' => getExistingCropsInLoan($item->id), 'exposure' => calcLoanExposure($item), 'fee_processing' => (double) $feeProc, 'fee_service' => (double) $feeSvc, 'fee_total' => getFeeTotal($item, (double) $feeProc + (double) $feeSvc), 'fee_onTotal' => (bool) $item->financials['fee_onTotal'], 'int_arm' => getARMInterestAlt($commitArm, $estDays, $intPercentArm), 'int_dist' => getDistInterestAlt($commitDist, $estDays, $intPercentDist), 'int_total' => getARMInterestAlt($commitArm, $estDays, $intPercentArm) + getDistInterestAlt($commitDist, $estDays, $intPercentDist), 'int_percent_arm' => (double) $intPercentArm, 'int_percent_dist' => (double) $intPercentDist, 'other_cat_expense' => getPartyCatTotalExpenses($item->id, 'other'), 'other_collateral' => getOtherCollateralValueAndDiscount($item), 'other_crop_commit' => getPartyCropsCommit($item->id, 'other'), 'principal_arm' => $commitArm + getFeeTotal($item, (double) $feeProc + (double) $feeSvc), 'principal_dist' => $commitDist, 'principal_other' => $commitOther, 'prior_lien_total' => (double) getPriorLienTotal($item->id), 'proc_fee' => getFeeProc_armAndDist($item, $feeProc), 'proc_fee_arm_only' => getFeeProc_armOnly($item, $feeProc), 'srvc_fee' => getFeeService_armAndDist($item, $feeSvc), 'srvc_fee_arm_only' => getFeeService_armOnly($item, $feeSvc), 'sup_ins' => getSupIns($item->id), 'total_acres' => (double) $total_acres[0]->Total, 'total_farm_expenses' => (double) getTotalLoanFarmExpenses($item->id), 'total_fee_percent' => (double) $feeProc + (double) $feeSvc, 'total_fsa_pay' => (double) getTotalFSA($item), 'total_indirect' => (double) getTotalIndirectIncome($item)], 'id' => $item->id, 'slug' => makeSlug($item), 'account_classification' => $item->account_classification, 'added_land' => (bool) $item->added_land, 'added_land_verified' => (int) $item->added_land_verified, 'addendum_type' => (int) $item->addendum_type, 'addendums' => $item->has_addendum ? processAddendum($item->id) : [], 'agencies' => getLoanAgencies($item->id), 'agents' => $item->agents, 'analyst' => $item->analyst->name, 'analyst_can_approve' => (bool) $item->analyst_can_approve, 'analyst_can_submit' => (bool) $item->analyst_can_submit, 'analyst_abr' => $item->analyst->nick, 'analyst_email' => $item->analyst->email, 'analyst_id' => $item->analyst->id, 'area_acres' => getAreaAcres($item->id), 'aoi_received' => (int) $item->aoi_received, 'app_date' => $item->app_date, 'applicant' => $item->applicants, 'arm_approved' => (int) $item->arm_approved, 'arm_ucc_received' => (int) $item->arm_ucc_received, 'attachments' => $item->attachments, 'bankruptcy_history' => (bool) $item->bankruptcy_history, 'bankruptcy_order_received' => (int) $item->bankruptcy_order_received, 'buyers' => $item->buyers, 'ccc_received' => (int) $item->ccc_received, 'closingdocs' => $item->closingdocs, 'committee' => $item->committee, 'committee_vote' => committeeVote($item->id), 'comments' => $item->comments, 'conditions_aci' => (bool) $item->conditions_aci, 'conditions_adis' => (bool) $item->conditions_adis, 'conditions_afsa' => (bool) $item->conditions_afsa, 'conditions_areb' => (bool) $item->conditions_areb, 'conditions_asa' => (bool) $item->conditions_asa, 'conditions_cd' => (bool) $item->conditions_cd, 'conditions_ccl' => (bool) $item->conditions_ccl, 'conditions_pg' => (bool) $item->conditions_pg, 'controlled_disbursement' => (bool) $item->controlled_disbursement, 'crop_certified' => (int) $item->crop_certified, 'crophail' => $item->crophail, 'crop_inspection' => (int) $item->crop_inspection, 'crop_loan' => (bool) $cropLoan, 'crop_year' => (int) $item->crop_year, 'databases' => processAPHDBS($item), 'decision_date' => $item->decision_date, 'default_due_date' => $item->default_due_date, 'dist_approved' => (int) $item->dist_approved, 'disbursement_issue' => (bool) $item->disbursement_issue, 'disbursements' => $item->disbursements, 'distributor' => $item->distributor ? $item->distributor : [], 'dist_ucc_received' => (int) $item->dist_ucc_received, 'due_date' => $item->due_date, 'equipment_collateral' => (bool) $item->equipment_collateral, 'est_days' => (double) $estDays, 'exceptions' => $item->exceptions, 'expenses' => $item->expenses, 'farmer' => $item->farmers, 'farmexpenses' => $item->farmexpenses, 'farms' => $item->farms, 'farmunits' => processFarmUnits($item), 'financials' => $item->financials, 'fsa_compliant' => (int) $item->fsa_compliant, 'fsapayments' => $item->fsapayments, 'full_season' => $fullSeason, 'grade' => $item->grade, 'has_addendum' => (bool) $item->has_addendum, 'has_attachments' => $hasAttachments, 'has_distributor' => (bool) $item->has_distributor, 'indyinc' => $item->indyinc, 'inspols' => $item->inspols, 'ins_summary' => getInsuranceCropSummaryByLoan($item->id), 'is_active' => (bool) $item->is_active, 'is_xcolled' => (bool) $item->is_xcolled, 'is_fast_tracked' => (bool) $item->is_fast_tracked, 'is_stale' => (bool) $isStale, 'is_watched' => (bool) $item->is_watched, 'its_list' => (int) $item->its_list, 'leases_valid' => (int) $item->leases_valid, 'lien_letter_received' => (int) $item->lien_letter_received, 'limit_warning' => (int) $item->limit_warning, 'limit_warning_message' => $item->limit_warning_message, 'loan_closed' => (int) $item->loan_closed, 'loan_closed_date' => $item->loan_closed_date ? Carbon::createFromFormat('Y-m-d', $item->loan_closed_date)->format('m/d/Y') : '', 'loanconditions' => $item->conditions, 'loancrops' => addAcres($item->loancrops), 'loandistributor' => $item->loandistributor, 'loanpractices' => $item->practices, 'loan_type' => $item->loantypes->loantype, 'loan_type_id' => (int) $item->loan_type_id, 'loantype_abr' => $item->loantypes->abr, 'location' => $item->location, 'loc_abr' => $item->location->loc_abr, 'other_collateral' => $item->othercollateral, 'past_due' => $pastDue, 'permission_to_insure_verified' => (int) $item->permission_to_insure_verified, 'planned_crops' => $item->plannedcrops, 'prev_lien_verified' => (int) $item->prev_lien_verified, 'prior_liens' => $item->priorliens, 'quests' => ['amount_requested' => (double) $item->quests->amount_requested, 'plant_own' => (bool) $item->quests->plant_own, 'plant_own_details' => $item->quests->plant_own_details, 'harvest_own' => (bool) $item->quests->harvest_own, 'harvest_own_details' => $item->quests->harvest_own_details, 'equip_obligations' => (bool) $item->quests->equip_obligations, 'equip_obligations_details' => $item->quests->equip_obligations_details, 'other_cash' => (bool) $item->quests->other_cash, 'other_cash_details' => $item->quests->other_cash_details, 'insInPlace' => (bool) $item->quests->insInPlace, 'insInPlace_details' => $item->quests->insInPlace_details, 'fsa_good' => (bool) $item->quests->fsa_good, 'fsa_good_details' => $item->quests->fsa_good_details, 'fci_good' => (bool) $item->quests->fci_good, 'fci_good_details' => $item->quests->fci_good_details, 'premiums_past' => (bool) $item->quests->premiums_past, 'premiums_details' => $item->quests->premiums_details, 'legal_defendant' => (bool) $item->quests->legal_defendant, 'defendant_details' => $item->quests->defendant_details, 'judgements' => (bool) $item->quests->judgements, 'judgement_details' => $item->quests->judgement_details, 'bankruptcy' => (bool) $item->quests->bankruptcy, 'bankruptcy_details' => $item->quests->bankruptcy_details, 'bankruptcy_order' => (bool) $item->quests->bankruptcy_order, 'liens' => (bool) $item->quests->liens, 'liens_details' => $item->quests->liens_details, 'fsa_direct_pay' => (bool) $item->quests->fsa_direct_pay, 'fsa_direct_pay_details' => $item->quests->fsa_direct_pay_details, 'future_liabilities' => (bool) $item->quests->future_liabilities, 'credit_3p_available' => (bool) $item->quests->credit_3p_available, 'credit_3p_details' => $item->quests->credit_3p_details, 'income_percent' => (double) $item->quests->income_percent, 'income_distribution_details' => $item->quests->income_distribution_details, 'distributor' => $item->quests->distributor, 'agency' => $item->quests->agency, 'pesticide_number' => $item->quests->pesticide_number, 'pest_num_expiration' => $item->quests->pest_num_expiration, 'credit_score' => (int) $item->quests->credit_score, 'affiliates' => (bool) $item->quests->affiliates, 'affiliated_entities' => $item->quests->affiliated_entities, 'farm_supplier_creditors' => $item->quests->farm_supplier_creditors], 'rebators' => $item->rebators, 'references' => $item->references, 'realestate_collateral' => (bool) $item->realestate_collateral, 'rebate_assignment' => (int) $item->rebate_assignment, 'received_3party' => (int) $item->received_3party, 'recommended' => (int) $item->recommended, 'reconciliation' => (int) $item->reconciliation, 'region' => $item->location->regions->region, 'required_3party' => (bool) $item->required_3party, 'season' => $item->season, 'status' => $item->status, 'storage' => $item->storage, 'tabstats' => $item->tabstats, 'terms' => $item->termmods, 'transactions' => $item->transactions, 'xcols' => getXCols($item->id)];
 }
function saveDATA($uid, $title, $slug, $old_slug, $date, $status, $content, $tags, $inFeed)
{
    $slug = makeSlug($slug);
    $save = false;
    $modifier = "";
    $workingSlug = $slug;
    while (!$save) {
        if (file_exists("data/{$workingSlug}.md")) {
            $PAGE = loadDATA($workingSlug);
            if ($PAGE["UID"] == $uid) {
                $save = true;
            }
        } else {
            $save = true;
        }
        if ($save) {
            if (!$uid) {
                $uid = md5(time() . rand());
            }
            $md = "UID: {$uid}\nTitle: {$title}\nSlug: {$workingSlug}\nPublish Date: {$date}\nStatus: {$status}\nTags: {$tags}\nIn Feed: {$inFeed}\n\n{$content}";
            file_put_contents("data/{$workingSlug}.md", $md);
            if ($old_slug && $old_slug != $workingSlug && file_exists("data/{$old_slug}.md")) {
                unlink("data/{$old_slug}.md");
            }
            return true;
        } else {
            $modifier++;
            $workingSlug = $slug . "-" . ($modifier + 1);
        }
    }
}
Exemple #3
0
 public function login($user, $password)
 {
     $userslug = makeSlug($user);
     $tablename = $this->prefix . "users";
     // for once we don't use getUser(), because we need the password.
     $user = $this->db->fetchAssoc("SELECT * FROM {$tablename} WHERE username='******'");
     if (empty($user)) {
         $this->session->setFlash('error', 'Username or password not correct. Please check your input.');
         return false;
     }
     require_once __DIR__ . "/phpass/PasswordHash.php";
     $hasher = new PasswordHash(8, TRUE);
     if ($hasher->CheckPassword($password, $user['password'])) {
         if (!$user['enabled']) {
             $this->session->setFlash('error', 'Your account is disabled. Sorry about that.');
             return false;
         }
         $update = array('lastseen' => date('Y-m-d H:i:s'), 'lastip' => $_SERVER['REMOTE_ADDR']);
         $this->db->update($tablename, $update, array('id' => $user['id']));
         $user = $this->getUser($user['id']);
         $this->session->start();
         $this->session->set('user', $user);
         $this->session->setFlash('success', "You've been logged on successfully.");
         return true;
     } else {
         $this->session->setFlash('error', 'Username or password not correct. Please check your input.');
         return false;
     }
 }
Exemple #4
0
 function record(Silex\Application $app, $contenttypeslug, $slug)
 {
     $contenttype = $app['storage']->getContentType($contenttypeslug);
     $slug = makeSlug($slug);
     // First, try to get it by slug.
     $content = $app['storage']->getSingleContent($contenttype['slug'], array('slug' => $slug));
     if (!$content && is_numeric($slug)) {
         // And otherwise try getting it by ID
         $content = $app['storage']->getSingleContent($contenttype['slug'], array('id' => $slug));
     }
     // No content, no page!
     if (!$content) {
         $app->abort(404, "Page {$contenttypeslug}/{$slug} not found.");
     }
     // Then, select which template to use, based on our 'cascading templates rules'
     $template = $content->template();
     // Fallback: If file is not OK, show an error page
     $filename = $app['paths']['themepath'] . "/" . $template;
     if (!file_exists($filename) || !is_readable($filename)) {
         $app->abort(404, "No template for '" . $content->getTitle() . "' defined. Tried to use '{$template}'.");
     }
     $app['editlink'] = path('editcontent', array('contenttypeslug' => $contenttypeslug, 'id' => $content->id));
     $body = $app['twig']->render($template, array('record' => $content, $contenttype['singular_slug'] => $content));
     return new Response($body, 200, array('Cache-Control' => 's-maxage=3600, public'));
 }
function saveRecipe($recipe)
{
    //gets connection and database
    require 'connect.php';
    require_once 'makeSlug.php';
    if (isset($recipe['recipeTitle'], $recipe['type'], $recipe['description'])) {
        $title = trim($recipe['recipeTitle']);
        //removes whitespace before and after
        $slug = makeSlug($title);
        //Make sure this is unique
        $recipe['slug'] = $slug;
        //$feature = $recipe['featureImage'];
        $type = $recipe['type'];
        $description = $recipe['description'];
        //-----Recipe------
        //"recipe" handles basic information
        $query = "INSERT INTO recipe (title, slug, type, description)\n\t\tVALUES('{$title}', '{$slug}', '{$type}', '{$description}')";
        if (mysqli_query($conn, $query)) {
            //$response =  json_decode($slug);
            //echo($response);
            $recipe['recipeId'] = mysqli_insert_id($conn);
            //Need to be stored for later
            echo json_encode($recipe);
            //This id can be used in the allergy and ingredientlist later
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
        /*Allergy list has been removed for  some time*/
        /*Ingredient list not yet created*/
        /*Missing xBenefit*/
    } else {
        echo "Missing data";
    }
    //Make sure that the slug is unique, if not, add a number
    //http://stackoverflow.com/questions/15971685/creating-unique-page-title-slugs-php/15972027#15972027
    //Need to make sure the slugs are unique
    /*function makeUniqueSlug($string){
    		$query "SELECT slug 
    				FROM recipe
    				WHERE slug LIKE '$string'"
    		$response = mysql_query($conn $query);
    
    		if($response){
    
    			while ($response->fetch_row()) {
    				if (condition) {
    					# code...
    				}
    			}
    			return $slug;
    
    		} else{
    			echo "Couldnt issue database query while comparing slug: ";
    			echo mysqli_error($conn);
    		}
    
    	}*/
}
Exemple #6
0
 /**
  * Login page.
  */
 function login(Silex\Application $app, Request $request)
 {
     if ($request->getMethod() == "POST") {
         $username = makeSlug($request->get('username'));
         // echo "<pre>\n" . print_r($request->get('username') , true) . "</pre>\n";
         $result = $app['users']->login($request->get('username'), $request->get('password'));
         if ($result) {
             $app['log']->add("Login " . $request->get('username'), 2, '', 'login');
             return redirect('dashboard');
         }
     }
     $app['twig']->addGlobal('title', "Login");
     return $app['twig']->render('login.twig');
 }
Exemple #7
0
 public static function record(Silex\Application $app, $contenttypeslug, $slug)
 {
     $contenttype = $app['storage']->getContentType($contenttypeslug);
     $slug = makeSlug($slug, -1);
     // First, try to get it by slug.
     $content = $app['storage']->getContent($contenttype['slug'], array('slug' => $slug, 'returnsingle' => true));
     if (!$content && is_numeric($slug)) {
         // And otherwise try getting it by ID
         $content = $app['storage']->getContent($contenttype['slug'], array('id' => $slug, 'returnsingle' => true));
     }
     // No content, no page!
     if (!$content) {
         // There's one special edge-case we check for: if the request is for the backend, without trailing
         // slash and it is intercepted by custom routing, we forward the client to that location.
         if ($slug == trim($app['config']->get('general/branding/path'), "/")) {
             simpleredirect($app['config']->get('general/branding/path') . "/");
         }
         $app->abort(404, "Page {$contenttypeslug}/{$slug} not found.");
     }
     // Then, select which template to use, based on our 'cascading templates rules'
     $template = $content->template();
     // Fallback: If file is not OK, show an error page
     $filename = $app['paths']['themepath'] . "/" . $template;
     if (!file_exists($filename) || !is_readable($filename)) {
         $error = sprintf("No template for '%s' defined. Tried to use '%s/%s'.", $content->getTitle(), basename($app['config']->get('general/theme')), $template);
         $app['log']->setValue('templateerror', $error);
         $app->abort(404, $error);
     }
     // Setting the canonical path and the editlink.
     $app['canonicalpath'] = $content->link();
     $app['paths'] = getPaths($app);
     $app['editlink'] = path('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => $content->id));
     $app['edittitle'] = $content->getTitle();
     // Make sure we can also access it as {{ page.title }} for pages, etc. We set these in the global scope,
     // So that they're also available in menu's and templates rendered by extensions.
     $app['twig']->addGlobal('record', $content);
     $app['twig']->addGlobal($contenttype['singular_slug'], $content);
     // Render the template and return.
     return $app['render']->render($template);
 }
Exemple #8
0
 /**
  * Load the configuration from the various YML files.
  */
 public function getConfig()
 {
     $config = array();
     // Read the config
     $config['general'] = array_merge($this->parseConfigYaml('config.yml'), $this->parseConfigYaml('config_local.yml'));
     $config['taxonomy'] = $this->parseConfigYaml('taxonomy.yml');
     $tempContentTypes = $this->parseConfigYaml('contenttypes.yml');
     $config['menu'] = $this->parseConfigYaml('menu.yml');
     $config['routing'] = $this->parseConfigYaml('routing.yml');
     $config['permissions'] = $this->parseConfigYaml('permissions.yml');
     $config['extensions'] = array();
     // fetch the theme config. requires special treatment due to the path
     $this->app['resources']->initializeConfig($config);
     $paths = $this->app['resources']->getPaths();
     $themeConfigFile = $paths['themepath'] . '/config.yml';
     $config['theme'] = $this->parseConfigYaml($themeConfigFile, array(), false);
     // @todo: If no config files can be found, get them from bolt.cm/files/default/
     $this->paths = $this->app['resources']->getPaths();
     $this->setDefaults();
     // Make sure old settings for 'contentsCss' are still picked up correctly
     if (isset($config['general']['wysiwyg']['ck']['contentsCss'])) {
         $config['general']['wysiwyg']['ck']['contentsCss'] = array(1 => $config['general']['wysiwyg']['ck']['contentsCss']);
     }
     // Make sure old settings for 'accept_file_types' are not still picked up. Before 1.5.4 we used to store them
     // as a regex-like string, and we switched to an array. If we find the old style, fall back to the defaults.
     if (isset($config['general']['accept_file_types']) && !is_array($config['general']['accept_file_types'])) {
         unset($config['general']['accept_file_types']);
     }
     // Merge the array with the defaults. Setting the required values that aren't already set.
     $config['general'] = array_merge_recursive_distinct($this->defaultConfig, $config['general']);
     // Make sure the cookie_domain for the sessions is set properly.
     if (empty($config['general']['cookies_domain'])) {
         if (isset($_SERVER['HTTP_HOST'])) {
             $hostname = $_SERVER['HTTP_HOST'];
         } elseif (isset($_SERVER['SERVER_NAME'])) {
             $hostname = $_SERVER['SERVER_NAME'];
         } else {
             $hostname = '';
         }
         // Don't set the domain for a cookie on a "TLD" - like 'localhost', or if the server_name is an IP-address
         if (strpos($hostname, '.') > 0 && preg_match("/[a-z0-9]/i", $hostname)) {
             if (preg_match("/^www[0-9]*./", $hostname)) {
                 $config['general']['cookies_domain'] = '.' . preg_replace("/^www[0-9]*./", '', $hostname);
             } else {
                 $config['general']['cookies_domain'] = '.' . $hostname;
             }
             // Make sure we don't have consecutive '.'-s in the cookies_domain..
             $config['general']['cookies_domain'] = str_replace('..', '.', $config['general']['cookies_domain']);
         } else {
             $config['general']['cookies_domain'] = '';
         }
     }
     // Make sure Bolt's mount point is OK:
     $config['general']['branding']['path'] = '/' . safeString($config['general']['branding']['path']);
     // Make sure $config['taxonomy'] is an array. (if the file is empty, YAML parses it as NULL)
     if (empty($config['taxonomy'])) {
         $config['taxonomy'] = array();
     }
     // Clean up taxonomies
     foreach ($config['taxonomy'] as $key => $value) {
         if (!isset($config['taxonomy'][$key]['name'])) {
             $config['taxonomy'][$key]['name'] = ucwords($config['taxonomy'][$key]['slug']);
         }
         if (!isset($config['taxonomy'][$key]['singular_name'])) {
             if (isset($config['taxonomy'][$key]['singular_slug'])) {
                 $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['singular_slug']);
             } else {
                 $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['slug']);
             }
         }
         if (!isset($config['taxonomy'][$key]['slug'])) {
             $config['taxonomy'][$key]['slug'] = strtolower(safeString($config['taxonomy'][$key]['name']));
         }
         if (!isset($config['taxonomy'][$key]['singular_slug'])) {
             $config['taxonomy'][$key]['singular_slug'] = strtolower(safeString($config['taxonomy'][$key]['singular_name']));
         }
         if (!isset($config['taxonomy'][$key]['has_sortorder'])) {
             $config['taxonomy'][$key]['has_sortorder'] = false;
         }
         // Make sure the options are $key => $value pairs, and not have implied integers for keys.
         if (!empty($config['taxonomy'][$key]['options']) && is_array($config['taxonomy'][$key]['options'])) {
             $options = array();
             // FIXME using $value variable seems bad idea because of outer loop uses too
             foreach ($config['taxonomy'][$key]['options'] as $optionkey => $value) {
                 if (is_numeric($optionkey)) {
                     $optionkey = makeSlug($value);
                     // was: strtolower(safeString($value));
                 }
                 $options[$optionkey] = $value;
             }
             $config['taxonomy'][$key]['options'] = $options;
         }
         // If taxonomy is like tags, set 'tagcloud' to true by default.
         if ($config['taxonomy'][$key]['behaves_like'] == 'tags' && !isset($config['taxonomy'][$key]['tagcloud'])) {
             $config['taxonomy'][$key]['tagcloud'] = true;
         }
     }
     // Clean up contenttypes
     $config['contenttypes'] = array();
     foreach ($tempContentTypes as $key => $temp) {
         // If the slug isn't set, and the 'key' isn't numeric, use that as the slug.
         if (!isset($temp['slug']) && !is_numeric($key)) {
             $temp['slug'] = makeSlug($key);
         }
         // If neither 'name' nor 'slug' is set, we need to warn the user. Same goes for when
         // neither 'singular_name' nor 'singular_slug' is set.
         if (!isset($temp['name']) && !isset($temp['slug'])) {
             $error = sprintf("In contenttype <code>%s</code>, neither 'name' nor 'slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
             $llc = new Configuration\LowlevelChecks($this->app['resources']);
             $llc->lowlevelError($error);
         }
         if (!isset($temp['singular_name']) && !isset($temp['singular_slug'])) {
             $error = sprintf("In contenttype <code>%s</code>, neither 'singular_name' nor 'singular_slug' is set. Please edit <code>contenttypes.yml</code>, and correct this.", $key);
             $llc = new Configuration\LowlevelChecks($this->app['resources']);
             $llc->lowlevelError($error);
         }
         if (!isset($temp['slug'])) {
             $temp['slug'] = makeSlug($temp['name']);
         }
         if (!isset($temp['singular_slug'])) {
             $temp['singular_slug'] = makeSlug($temp['singular_name']);
         }
         if (!isset($temp['show_on_dashboard'])) {
             $temp['show_on_dashboard'] = true;
         }
         if (!isset($temp['show_in_menu'])) {
             $temp['show_in_menu'] = true;
         }
         if (!isset($temp['sort'])) {
             $temp['sort'] = '';
         }
         if (!isset($temp['default_status'])) {
             $temp['default_status'] = 'draft';
         }
         // Make sure all fields are lowercase and 'safe'.
         $tempfields = $temp['fields'];
         $temp['fields'] = array();
         // Set a default group and groups array.
         $currentgroup = false;
         $temp['groups'] = array();
         foreach ($tempfields as $key => $value) {
             // FIXME Fix name 'keys' for fields
             $key = str_replace('-', '_', strtolower(safeString($key, true)));
             $temp['fields'][$key] = $value;
             // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == 'file' || $temp['fields'][$key]['type'] == 'filelist') {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array_intersect(array('doc', 'docx', 'txt', 'md', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'csv'), $config['general']['accept_file_types']);
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
             // If field is an "image" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == 'image' || $temp['fields'][$key]['type'] == 'imagelist') {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array_intersect(array('gif', 'jpg', 'jpeg', 'png'), $config['general']['accept_file_types']);
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
             // If the field has a 'group', make sure it's added to the 'groups' array, so we can turn
             // them into tabs while rendering. This also makes sure that once you started with a group,
             // all others have a group too.
             if (!empty($temp['fields'][$key]['group'])) {
                 $currentgroup = $temp['fields'][$key]['group'];
                 $temp['groups'][] = $currentgroup;
             } else {
                 $temp['fields'][$key]['group'] = $currentgroup;
             }
         }
         // Make sure the 'uses' of the slug is an array.
         if (isset($temp['fields']['slug']) && isset($temp['fields']['slug']['uses']) && !is_array($temp['fields']['slug']['uses'])) {
             $temp['fields']['slug']['uses'] = array($temp['fields']['slug']['uses']);
         }
         // Make sure taxonomy is an array.
         if (isset($temp['taxonomy']) && !is_array($temp['taxonomy'])) {
             $temp['taxonomy'] = array($temp['taxonomy']);
         }
         // when adding relations, make sure they're added by their slug. Not their 'name' or 'singular name'.
         if (!empty($temp['relations']) && is_array($temp['relations'])) {
             // FIXME using variable $key seems a bad idea while outer loop uses the same
             foreach ($temp['relations'] as $key => $relation) {
                 if ($key != makeSlug($key)) {
                     $temp['relations'][makeSlug($key)] = $temp['relations'][$key];
                     unset($temp['relations'][$key]);
                 }
             }
         }
         // Make sure the 'groups' has unique elements, if there are any.
         if (!empty($temp['groups'])) {
             $temp['groups'] = array_unique($temp['groups']);
         } else {
             unset($temp['groups']);
         }
         $config['contenttypes'][$temp['slug']] = $temp;
     }
     // Set all the distinctive arrays as part of our Config object.
     $this->data = $config;
 }
Exemple #9
0
 public function getUri($title, $id = 0, $contenttypeslug, $fulluri = true)
 {
     $contenttype = $this->getContentType($contenttypeslug);
     $tablename = $this->prefix . $contenttype['slug'];
     $id = intval($id);
     $fulluri = util::str_to_bool($fulluri);
     $slug = makeSlug($title);
     // don't allow strictly numeric slugs.
     if (is_numeric($slug)) {
         $slug = $contenttype['singular_slug'] . "-" . $slug;
     }
     // Only add 'entry/' if $full is requested.
     if ($fulluri) {
         $prefix = "/" . $contenttype['singular_slug'] . "/";
     }
     $query = "SELECT id from {$tablename} WHERE slug='{$slug}' and id!='{$id}';";
     $res = $this->db->query($query)->fetch();
     if (!$res) {
         $uri = $prefix . $slug;
     } else {
         for ($i = 1; $i <= 10; $i++) {
             $newslug = $slug . '-' . $i;
             $query = "SELECT id from {$tablename} WHERE slug='{$newslug}' and id!='{$id}';";
             $res = $this->db->query($query)->fetch();
             if (!$res) {
                 $uri = $prefix . $newslug;
                 break;
             }
         }
         // otherwise, just get a random slug.
         if (empty($uri)) {
             $slug = trimText($slug, 32, false, false) . "-" . makeKey(6);
             $uri = $prefix . $slug;
         }
     }
     return $uri;
 }
function create($entity)
{
    $html = getHTML($entity['source_url']);
    if (!$html) {
        return error_log('Could not import ' + $entity['source_url']);
    }
    // Clean title
    $entity['title'] = trim(html_entity_decode($entity['title'], ENT_COMPAT, 'UTF-8'));
    // Generate key
    $entity['key'] = 'ch/' . makeSlug($entity['title']);
    // Extract email
    $emailLink = $html->find('table.tabelleESK a[href^=mailto:]', 0);
    if ($emailLink) {
        $entity['email'] = str_replace('mailto:', '', trim($emailLink->href));
    }
    // Extract URL
    foreach ($html->find('table.tabelleESK tr') as $row) {
        $name = trim($row->children(0)->innertext);
        if (stripos('homepage', $name) !== false) {
            foreach ($row->children() as $i => $cell) {
                $link = $cell->find('a[href]', 0);
                if ($link) {
                    $entity['url'] = $link->href;
                    break;
                }
                // Ugly case: URL but no link
                if ($i && !$cell->children()) {
                    $entity['url'] = $cell->innertext;
                    break;
                }
            }
        }
    }
    // Find entity abbreviation
    $orgTitle = $html->find('h2.titleOrg', 0);
    if ($orgTitle) {
        $orgTitleParts = explode('-', $orgTitle->innertext);
        if (count($orgTitleParts) > 1) {
            $entity['abbr'] = trim(array_pop($orgTitleParts));
            $entity['abbr'] = html_entity_decode($entity['abbr'], ENT_COMPAT, 'UTF-8');
        }
    } else {
        error_log('No title on ' + $entity['source_url']);
    }
    // Find entity address
    $infoBlock = $html->find('div.infoblock', 0)->innertext;
    if (preg_match('/<\\/h2>(.+?)<div class="titleContent">/s', $infoBlock, $matches)) {
        $infoBlock = str_replace(array('<br>', '(neues Fenster)'), array(', ', ''), $matches[1]);
        $infoBlock = preg_replace('/\\s\\s+/', ' ', $infoBlock);
        $infoBlock = trim(html_entity_decode(strip_tags($infoBlock), ENT_COMPAT, 'UTF-8'));
        $entity['address'] = $infoBlock;
    }
    save($entity);
    getChildren($entity, $html);
}
Exemple #11
0
 /**
  * Load the configuration from the various YML files.
  */
 public function getConfig()
 {
     $config = array();
     // Read the config
     $config['general'] = array_merge($this->parseConfigYaml('config.yml'), $this->parseConfigYaml('config_local.yml'));
     $config['taxonomy'] = $this->parseConfigYaml('taxonomy.yml');
     $tempcontenttypes = $this->parseConfigYaml('contenttypes.yml');
     $config['menu'] = $this->parseConfigYaml('menu.yml');
     $config['routing'] = $this->parseConfigYaml('routing.yml');
     $config['permissions'] = $this->parseConfigYaml('permissions.yml');
     $config['extensions'] = array();
     // @todo: If no config files can be found, get them from bolt.cm/files/default/
     $this->paths = getPaths($config);
     $this->setDefaults();
     if (isset($config['general']['wysiwyg']['ck']['contentsCss'])) {
         $config['general']['wysiwyg']['ck']['contentsCss'] = array(1 => $config['general']['wysiwyg']['ck']['contentsCss']);
     }
     $config['general'] = array_merge_recursive_distinct($this->defaultconfig, $config['general']);
     // Make sure the cookie_domain for the sessions is set properly.
     if (empty($config['general']['cookies_domain'])) {
         if (isset($_SERVER['HTTP_HOST'])) {
             $hostname = $_SERVER['HTTP_HOST'];
         } elseif (isset($_SERVER['SERVER_NAME'])) {
             $hostname = $_SERVER['SERVER_NAME'];
         } else {
             $hostname = "";
         }
         // Don't set the domain for a cookie on a "TLD" - like 'localhost', or if the server_name is an IP-address
         if (strpos($hostname, ".") > 0 && preg_match("/[a-z0-9]/i", $hostname)) {
             if (preg_match("/^www[0-9]*./", $hostname)) {
                 $config['general']['cookies_domain'] = "." . preg_replace("/^www[0-9]*./", "", $hostname);
             } else {
                 $config['general']['cookies_domain'] = "." . $hostname;
             }
             // Make sure we don't have consecutive '.'-s in the cookies_domain..
             $config['general']['cookies_domain'] = str_replace("..", ".", $config['general']['cookies_domain']);
         } else {
             $config['general']['cookies_domain'] = "";
         }
     }
     // Make sure Bolt's mount point is OK:
     $config['general']['branding']['path'] = "/" . safeString($config['general']['branding']['path']);
     // Clean up taxonomies
     foreach ($config['taxonomy'] as $key => $value) {
         if (!isset($config['taxonomy'][$key]['name'])) {
             $config['taxonomy'][$key]['name'] = ucwords($config['taxonomy'][$key]['slug']);
         }
         if (!isset($config['taxonomy'][$key]['singular_name'])) {
             $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['singular_slug']);
         }
         if (!isset($config['taxonomy'][$key]['slug'])) {
             $config['taxonomy'][$key]['slug'] = strtolower(safeString($config['taxonomy'][$key]['name']));
         }
         if (!isset($config['taxonomy'][$key]['singular_slug'])) {
             $config['taxonomy'][$key]['singular_slug'] = strtolower(safeString($config['taxonomy'][$key]['singular_name']));
         }
         if (!isset($config['taxonomy'][$key]['has_sortorder'])) {
             $config['taxonomy'][$key]['has_sortorder'] = false;
         }
         // Make sure the options are $key => $value pairs, and not have implied integers for keys.
         if (!empty($config['taxonomy'][$key]['options']) && is_array($config['taxonomy'][$key]['options'])) {
             $options = array();
             foreach ($config['taxonomy'][$key]['options'] as $optionkey => $value) {
                 if (is_numeric($optionkey)) {
                     $optionkey = makeSlug($value);
                     // was: strtolower(safeString($value));
                 }
                 $options[$optionkey] = $value;
             }
             $config['taxonomy'][$key]['options'] = $options;
         }
         // If taxonomy is like tags, set 'tagcloud' to true by default.
         if ($config['taxonomy'][$key]['behaves_like'] == "tags" && !isset($config['taxonomy'][$key]['tagcloud'])) {
             $config['taxonomy'][$key]['tagcloud'] = true;
         }
     }
     // Clean up contenttypes
     $config['contenttypes'] = array();
     foreach ($tempcontenttypes as $temp) {
         if (!isset($temp['slug'])) {
             $temp['slug'] = makeSlug($temp['name']);
         }
         if (!isset($temp['singular_slug'])) {
             $temp['singular_slug'] = makeSlug($temp['singular_name']);
         }
         if (!isset($temp['show_on_dashboard'])) {
             $temp['show_on_dashboard'] = true;
         }
         if (!isset($temp['sort'])) {
             $temp['sort'] = "id";
         }
         // Make sure all fields are lowercase and 'safe'.
         $tempfields = $temp['fields'];
         $temp['fields'] = array();
         foreach ($tempfields as $key => $value) {
             // Fix name 'keys' for fields
             $key = str_replace("-", "_", strtolower(safeString($key, true)));
             $temp['fields'][$key] = $value;
             // If field is a "file" type, make sure the 'extensions' are set, and it's an array.
             if ($temp['fields'][$key]['type'] == "file") {
                 if (empty($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array('pdf', 'txt', 'md', 'doc', 'docx', 'zip', 'tgz');
                 }
                 if (!is_array($temp['fields'][$key]['extensions'])) {
                     $temp['fields'][$key]['extensions'] = array($temp['fields'][$key]['extensions']);
                 }
             }
         }
         // Make sure the 'uses' of the slug is an array.
         if (isset($temp['fields']['slug']) && isset($temp['fields']['slug']['uses']) && !is_array($temp['fields']['slug']['uses'])) {
             $temp['fields']['slug']['uses'] = array($temp['fields']['slug']['uses']);
         }
         // Make sure taxonomy is an array.
         if (isset($temp['taxonomy']) && !is_array($temp['taxonomy'])) {
             $temp['taxonomy'] = array($temp['taxonomy']);
         }
         $config['contenttypes'][$temp['slug']] = $temp;
     }
     // Set all the distinctive arrays as part of our Config object.
     $this->data = $config;
 }
Exemple #12
0
if (!empty($_GET['q'])) {

    $q = makeSlug($_GET['q']);

    $source = preg_replace_callback("/" . $q . "/i", function($matches) {
        $output = sprintf("<mark id='%s'>%s</mark>",
            makeSlug($matches[0]),
            $matches[0]
        );
        return $output;
    }, $source);
}
---- */
// Markup for <h1> and <h2>..
$source = preg_replace_callback("/<h([234])>(.*)<\\/h([234])>/i", function ($matches) {
    $output = sprintf("<h%s id='%s'>%s<a href='#%s' class='anchor'>¶</a></h%s>", $matches[1], makeSlug($matches[2]), $matches[2], makeSlug($matches[2]), $matches[1]);
    return $output;
}, $source);
$loader = new Twig_Loader_Filesystem('./view');
$twig = new Twig_Environment($loader, array());
// Add Dumper function to twig.
$dumper = new Twig_SimpleFunction('dump', function ($var) {
    return dump($var);
}, array('is_safe' => array('html')));
$twig->addFunction($dumper);
// Add markdown to twig.
$markdown = new Twig_SimpleFilter('markdown', function ($content) {
    return \ParsedownExtra::instance()->text($content);
}, array('is_safe' => array('html')));
$twig->addFilter($markdown);
// Add slug filter to twig.
Exemple #13
0
 /**
  * Return the 'sluggified' version of a string.
  *
  * @param $str string input value
  * @return string slug
  */
 public function slug($str)
 {
     $slug = makeSlug($str);
     return $slug;
 }
Exemple #14
0
 public function update($record, $data = array())
 {
     $this->db->where('id', $record->id)->update($this->table, array('title' => $this->input->post('title'), 'slug' => $this->input->post('autoSlug') === 'true' ? makeSlug($this->input->post('title')) : makeSlug($this->input->post('slug')), 'image' => $data['image']['name']));
     return $this->db->affected_rows();
 }
function lang($line, $convert = null)
{
    $slug = (!is_null($convert) ? $convert . '-' : '') . makeSlug($line);
    $trans = get_instance()->lang->line($slug);
    if (empty($trans)) {
        $trans = !is_null($convert) ? strConvert($line, $convert, get_instance()->language) : $line;
        $filepath = APPPATH . '/language/' . get_instance()->language . '/site_lang.php';
        $file = fopen($filepath, FOPEN_WRITE_CREATE);
        $data = '$lang[\'' . $slug . '\'] = \'' . $trans . '\';' . PHP_EOL;
        flock($file, LOCK_EX);
        fwrite($file, $data);
        flock($file, LOCK_UN);
        fclose($file);
        return $trans;
    }
    return $trans;
}
Exemple #16
0
 /**
  * Get 'content'
  *
  * usage:
  * To get 10 entries, in order: {% set entries = content('entries', {'limit': 10}) %}
  *
  * To get the latest single page: {% set page = content('page', {'order':'datecreated desc'}) %}
  *
  * To get 5 upcoming events: {% set events = content('events', {'order': 'date asc', 'where' => 'date < now()' }) %}
  */
 public function content($contenttypeslug, $params)
 {
     global $app;
     /* TODO: figure out if there's a way to do this without globals.. */
     $contenttype = $app['storage']->getContentType($contenttypeslug);
     // If the contenttype doesn't exist, return an empty array
     if (!$contenttype) {
         $app['log']->add("contenttype '{$contenttypeslug}' doesn't exist.", 1);
         return array();
     }
     if ($app['request']->query->get('page') != "") {
         $params['page'] = $app['request']->query->get('page');
     }
     if (makeSlug($contenttypeslug) == $contenttype['singular_slug'] || $params['limit'] == 1) {
         // If we used the singular version of the contenttype, or we specifically request only one result..
         $content = $app['storage']->getSingleContent($contenttypeslug, $params);
     } else {
         // Else, we get more than one result
         $content = $app['storage']->getContent($contenttypeslug, $params, $pager);
         $app['pager'] = $pager;
     }
     return $content;
 }
Exemple #17
0
 public function importPost($post, $dryrun = true)
 {
     // If the mapping is not defined, ignore it.
     if (empty($this->config['mapping'][$post['post_type']])) {
         return "<p>No mapping defined for posttype '" . $post['post_type'] . "'.</p>";
     }
     // Find out which mapping we should use.
     $mapping = $this->config['mapping'][$post['post_type']];
     // If the mapped contenttype doesn't exist in Bolt.
     if (!$this->app['storage']->getContentType($mapping['targetcontenttype'])) {
         return "<p>Bolt contenttype '" . $mapping['targetcontenttype'] . "' for posttype '" . $post['post_type'] . "' does not exist.</p>";
     }
     // Create the new Bolt Record.
     $record = new \Bolt\Content($this->app, $mapping['targetcontenttype']);
     // 'expand' the postmeta fields to regular fields.
     if (!empty($post['postmeta']) && is_array($post['postmeta'])) {
         foreach ($post['postmeta'] as $id => $keyvalue) {
             $post[$keyvalue['key']] = $keyvalue['value'];
         }
     }
     // Iterate through the mappings, see if we can find it.
     foreach ($mapping['fields'] as $from => $to) {
         if (isset($post[$from])) {
             // It's present in the fields.
             $value = $post[$from];
             switch ($from) {
                 case "post_parent":
                     if (!empty($value)) {
                         $value = $mapping['fields']['post_parent_contenttype'] . "/" . $value;
                     }
                     break;
                 case "post_date":
                     if (!empty($value)) {
                         // WXR seems to use only one date value.
                         $record->setValue('datechanged', $value);
                         $record->setValue('datecreated', $value);
                         $record->setValue('datepublish', $value);
                     }
                     break;
             }
             switch ($to) {
                 case "username":
                     $value = makeSlug($value);
                     break;
                 case "status":
                     if ($value == "publish") {
                         $value = "published";
                     }
                     if ($value == "future") {
                         $value = "timed";
                     }
                     break;
             }
             $record->setValue($to, $value);
         }
     }
     // Perhaps import the categories as well..
     if (!empty($mapping['category']) && !empty($post['terms'])) {
         foreach ($post['terms'] as $term) {
             if ($term['domain'] == 'category') {
                 $record->setTaxonomy($mapping['category'], $term['slug']);
                 if (!in_array($term['slug'], $this->foundcategories)) {
                     $this->foundcategories[] = $term['slug'];
                 }
             }
         }
     }
     if ($dryrun) {
         $output = "<p>Original WXR Post <b>\"" . $post['post_title'] . "\"</b> -&gt; Converted Bolt Record :</p>";
         $output .= \util::var_dump($post, true);
         $output .= \util::var_dump($record, true);
         $output .= "\n<hr>\n";
     } else {
         $this->app['storage']->saveContent($record);
         $output = "Import: " . $record->get('id') . " - " . $record->get('title') . " <small><em>";
         $output .= $this->memUsage() . "mb.</em></small><br>";
     }
     return $output;
 }
Exemple #18
0
 public function update($record, $data = array())
 {
     $this->db->where('id', $record->id)->update($this->table, array('title' => $this->input->post('title'), 'slug' => $this->input->post('autoSlug') === 'true' ? makeSlug($this->input->post('title')) : makeSlug($this->input->post('slug')), 'summary' => $this->input->post('summary'), 'detail' => $this->input->post('detail'), 'image' => $data['image']['name'], 'metaTitle' => $this->input->post('metaTitle'), 'metaDescription' => $this->input->post('metaDescription'), 'metaKeywords' => $this->input->post('metaKeywords')));
     return $this->db->affected_rows();
 }
 /**
  * Attempt to login a user with the given password
  *
  * @param  string $user
  * @param  string $password
  * @return bool
  */
 public function login($user, $password)
 {
     $userslug = makeSlug($user);
     // for once we don't use getUser(), because we need the password.
     $query = "SELECT * FROM " . $this->usertable . " WHERE username=?";
     $query = $this->app['db']->getDatabasePlatform()->modifyLimitQuery($query, 1);
     $user = $this->db->executeQuery($query, array($userslug), array(\PDO::PARAM_STR))->fetch();
     if (empty($user)) {
         $this->session->getFlashBag()->set('error', __('Username or password not correct. Please check your input.'));
         return false;
     }
     $hasher = new \Hautelook\Phpass\PasswordHash($this->hash_strength, true);
     if ($hasher->CheckPassword($password, $user['password'])) {
         if (!$user['enabled']) {
             $this->session->getFlashBag()->set('error', __('Your account is disabled. Sorry about that.'));
             return false;
         }
         $update = array('lastseen' => date('Y-m-d H:i:s'), 'lastip' => $this->remoteIP, 'failedlogins' => 0, 'throttleduntil' => $this->throttleUntil(0));
         // Attempt to update the last login, but don't break on failure.
         try {
             $this->db->update($this->usertable, $update, array('id' => $user['id']));
         } catch (\Doctrine\DBAL\DBALException $e) {
             // Oops. User will get a warning on the dashboard about tables that need to be repaired.
         }
         $user = $this->getUser($user['id']);
         $user['sessionkey'] = $this->getAuthToken($user['username']);
         // We wish to create a new session-id for extended security, but due to a bug in PHP < 5.4.11, this
         // will throw warnings. Suppress them here. #shakemyhead
         // @see: https://bugs.php.net/bug.php?id=63379
         @$this->session->migrate(true);
         $this->session->set('user', $user);
         $this->session->getFlashBag()->set('success', __("You've been logged on successfully."));
         $this->currentuser = $user;
         $this->setAuthToken();
         return true;
     } else {
         $this->session->getFlashBag()->set('error', __('Username or password not correct. Please check your input.'));
         $this->app['log']->add("Failed login attempt for '" . $user['displayname'] . "'.", 3, '', 'issue');
         // Update the failed login attempts, and perhaps throttle the logins.
         $update = array('failedlogins' => $user['failedlogins'] + 1, 'throttleduntil' => $this->throttleUntil($user['failedlogins'] + 1));
         // Attempt to update the last login, but don't break on failure.
         try {
             $this->db->update($this->usertable, $update, array('id' => $user['id']));
         } catch (\Doctrine\DBAL\DBALException $e) {
             // Oops. User will get a warning on the dashboard about tables that need to be repaired.
         }
         // Take a nap, to prevent brute-forcing. Zzzzz...
         sleep(1);
         return false;
     }
 }
Exemple #20
0
    if (strlen($p["Tags"]) > 1) {
        $tagList = "<br /><strong>Tags:</strong> ";
        $tags = explode(",", $p["Tags"]);
        foreach ($tags as $tag) {
            $tagList .= "<a href=\"index-of-" . makeSlug(trim($tag)) . ".html\">" . trim($tag) . "</a> ";
        }
        $output = str_replace("{tag-list}", $tagList, $output);
    }
    $output = str_replace("{tag-list}", $tagList, $output);
    file_put_contents("../blog/{$p["Slug"]}.html", $output);
    $new_files[] = $p["Slug"] . ".html";
    // Add to menu pages
    if (strlen($p["Tags"]) > 1) {
        $tags = explode(",", $p["Tags"]);
        foreach ($tags as $tag) {
            $tag = makeSlug(trim($tag));
            if (!isset($tagPages[$tag])) {
                $tagPages[$tag] = array();
            }
            $tagPages[$tag][] = array($p["Publish Date"], $p["Title"], $p["Slug"]);
        }
    }
}
// make index pages...
foreach ($tagPages as $tpk => $tpv) {
    $myBody = "";
    foreach ($tpv as $p) {
        $myBody .= "<a href=\"{$p[2]}.html\">{$p[1]}</a> <small>({$p[0]})</small><br />";
    }
    $output = str_replace("{title}", "Index of posts tagged with: {$tpk}", $template);
    $output = str_replace("{tags}", $tpk, $output);
Exemple #21
0
 /**
  * Get the tablename with prefix from a given $name
  *
  * @param $name
  * @return mixed
  */
 protected function getTablename($name)
 {
     $name = str_replace("-", "_", makeSlug($name));
     $tablename = sprintf("%s%s", $this->prefix, $name);
     return $tablename;
 }
Exemple #22
0
function getConfig()
{
    $config = array();
    // Read the config
    $yamlparser = new Symfony\Component\Yaml\Parser();
    $config['general'] = $yamlparser->parse(file_get_contents(__DIR__ . '/../config/config.yml'));
    $config['taxonomy'] = $yamlparser->parse(file_get_contents(__DIR__ . '/../config/taxonomy.yml'));
    $tempcontenttypes = $yamlparser->parse(file_get_contents(__DIR__ . '/../config/contenttypes.yml'));
    $config['menu'] = $yamlparser->parse(file_get_contents(__DIR__ . '/../config/menu.yml'));
    // TODO: If no config files can be found, get them from bolt.cm/files/default/
    // echo "<pre>\n" . util::var_dump($config['menu'], true) . "</pre>\n";
    // Assume some sensible defaults for some options
    $defaultconfig = array('sitename' => 'Default Bolt site', 'homepage' => 'page/*', 'homepage_template' => 'index.twig', 'recordsperpage' => 10, 'recordsperdashboardwidget' => 5, 'debug' => false, 'strict_variables' => false, 'theme' => "default", 'debug_compressjs' => true, 'debug_compresscss' => true, 'listing_template' => 'listing.twig', 'listing_records' => '5', 'wysiwyg_images' => false, 'wysiwyg_tables' => false, 'wysiwyg_embed' => false, 'wysiwyg_fontcolor' => false, 'wysiwyg_align' => false, 'canonical' => $_SERVER['HTTP_HOST'], 'developer_notices' => false, 'cookies_use_remoteaddr' => true, 'cookies_use_browseragent' => false, 'cookies_use_httphost' => true, 'cookies_https_only' => false, 'cookies_lifetime' => 14 * 24 * 3600);
    $config['general'] = array_merge($defaultconfig, $config['general']);
    // TODO: Think about what to do with these..
    /*
    # Date and Time formats
    shortdate: j M ’ye
    longdate: l j F Y
    shorttime: H:i
    longtime: H:i:s
    fulldatetime: Y-m-d H:i:s
    */
    // Clean up taxonomies
    foreach ($config['taxonomy'] as $key => $value) {
        if (!isset($config['taxonomy'][$key]['name'])) {
            $config['taxonomy'][$key]['name'] = ucwords($config['taxonomy'][$key]['slug']);
        }
        if (!isset($config['taxonomy'][$key]['singular_name'])) {
            $config['taxonomy'][$key]['singular_name'] = ucwords($config['taxonomy'][$key]['singular_slug']);
        }
    }
    // Clean up contenttypes
    $config['contenttypes'] = array();
    foreach ($tempcontenttypes as $temp) {
        if (!isset($temp['slug'])) {
            $temp['slug'] = makeSlug($temp['name']);
        }
        if (!isset($temp['singular_slug'])) {
            $temp['singular_slug'] = makeSlug($temp['singular_name']);
        }
        if (!isset($temp['show_on_dashboard'])) {
            $temp['show_on_dashboard'] = true;
        }
        if (!isset($temp['sort'])) {
            $temp['sort'] = "";
        }
        $config['contenttypes'][$temp['slug']] = $temp;
    }
    // Get the script's filename, but _without_ SCRIPT_FILENAME
    $scripturi = str_replace("#" . dirname($_SERVER['SCRIPT_NAME']), '', "#" . $_SERVER['REQUEST_URI']);
    // I don't think we can set Twig's path in runtime, so we have to resort to hackishness to set the path..
    // If the request URI starts with '/bolt' in the URL, we assume we're in the Backend.. Yeah.. Awesome..
    if (strpos($scripturi, "bolt") === false) {
        $config['twigpath'] = array(realpath(__DIR__ . '/../../theme/' . basename($config['general']['theme'])), realpath(__DIR__ . '/../view'), realpath(__DIR__ . '/../extensions'));
    } else {
        $config['twigpath'] = array(realpath(__DIR__ . '/../view'), realpath(__DIR__ . '/../extensions'));
    }
    return $config;
}